Условие на последний элемент массива с использованием шаблона handlebars.js
Я использую handlebars.js для моего механизма шаблонов и хочу сделать отображение условного сегмента только в том случае, если это последний элемент массива, содержащийся в объекте конфигурации шаблонов.
{
columns: [{<obj>},{<obj>},{<obj>},{<obj>},{<obj>}]
}
Я уже потянул помощника, чтобы выполнить сравнение равенства/больше/меньше, чем сравнение, и имел успех идентифицировать исходный элемент таким образом, но мне не удавалось получить доступ к моей длине массива.
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {...})
"{{#each_with_index columns}}"+
"<div class='{{#equal index 0}} first{{/equal}}{{#equal index ../columns.length()}} last{{/equal}}'>"+
"</div>"+
"{{/each_with_index}}"
Кто-нибудь знает ярлык, другой подход и некоторую поддержку рулей, которая не даст мне оторваться от механизма handlebars.js, чтобы определить лучший курс?
Ответы
Ответ 1
Как и в Handlebars v1.1.0, вы можете использовать @first
и @last
булевы в каждом помощнике для этой проблемы:
{{#each foo}}
<div class='{{#if @first}}first{{/if}}
{{#if @last}} last{{/if}}'>
{{@key}} - {{@index}}
</div>
{{/each}}
Быстрый помощник, который я написал, чтобы сделать трюк:
Handlebars.registerHelper("foreach",function(arr,options) {
if(options.inverse && !arr.length)
return options.inverse(this);
return arr.map(function(item,index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length-1;
return options.fn(item);
}).join('');
});
Затем вы можете написать:
{{#foreach foo}}
<div class='{{#if $first}} first{{/if}}{{#if $last}} last{{/if}}'></div>
{{/foreach}}
Ответ 2
Так как Handlebars 1.1.0, первый и последний стал родным для каждого помощника. См. Билет # 483.
Использование похоже на класс помощника Эберанова:
{{#each foo}}
<div class='{{#if @first}}first{{/if}}{{#if @last}} last{{/if}}'>{{@key}} - {{@index}}</div>
{{/each}}
Ответ 3
Если вы просто попытаетесь обработать первый элемент массива, это может помочь
{{#each data-source}}{{#if @index}},{{/if}}"{{this}}"{{/each}}
@index предоставляется каждым помощником и для первого элемента, он будет равен нулю и, следовательно, может обрабатываться хэдпером.
Ответ 4
Решение:
<div class='{{#compare index 1}} first{{/compare}}{{#compare index total}} last{{/compare}}'></div>
Использование помощников из следующего блога и сущности...
https://gist.github.com/2889952
http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/
// {{#each_with_index records}}
// <li class="legend_item{{index}}"><span></span>{{Name}}</li>
// {{/each_with_index}}
Handlebars.registerHelper("each_with_index", function(array, fn) {
var total = array.length;
var buffer = "";
//Better performance: http://jsperf.com/for-vs-foreach/2
for (var i = 0, j = total; i < j; i++) {
var item = array[i];
// stick an index property onto the item, starting with 1, may make configurable later
item.index = i+1;
item.total = total;
// show the inside of the block
buffer += fn(item);
}
// return the finished buffer
return buffer;
});
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
operator = options.hash.operator || "==";
var operators = {
'==': function(l,r) { return l == r; },
'===': function(l,r) { return l === r; },
'!=': function(l,r) { return l != r; },
'<': function(l,r) { return l < r; },
'>': function(l,r) { return l > r; },
'<=': function(l,r) { return l <= r; },
'>=': function(l,r) { return l >= r; },
'typeof': function(l,r) { return typeof l == r; }
}
if (!operators[operator])
throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);
var result = operators[operator](lvalue,rvalue);
if( result ) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Обратите внимание, что начальный индекс указан правильно.
Ответ 5
Я немного улучшил помощника из Matt Brennan, вы можете использовать этот помощник с объектами или массивами, это решение требуется Underscore библиотека:
Handlebars.registerHelper("foreach", function(context, options) {
options = _.clone(options);
options.data = _.extend({}, options.hash, options.data);
if (options.inverse && !_.size(context)) {
return options.inverse(this);
}
return _.map(context, function(item, index, list) {
var intIndex = _.indexOf(_.values(list), item);
options.data.key = index;
options.data.index = intIndex;
options.data.isFirst = intIndex === 0;
options.data.isLast = intIndex === _.size(list) - 1;
return options.fn(item, options);
}).join('');
});
Использование:
{{#foreach foo}}
<div class='{{#if @first}}first{{/if}}{{#if @last}} last{{/if}}'>{{@key}} - {{@index}}</div>
{{/foreach}}