车把-不是每个而是一些 [英] Handlebars - Not each but some
本文介绍了车把-不是每个而是一些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为项目使用把手,并且我有一个包含10个项目的数据文件.我正在使用每个"命令将它们全部显示在一个页面上(效果很好),但是对于另一页面,我只想显示前4个项目.我怎样才能做到这一点?预先感谢!
I am using handlebars for a project and I have a data file with 10 items in it. I am using the 'each' command to show them all on one page (which works fine) but for another page i would like to show only the first 4 items. How can I do this? Thanks in advance!
推荐答案
您可以在{{#each}}循环中使用@index变量,并使用自定义帮助程序来测试@index的值.查看下面适合您需要的代码段.
You can do that with the @index variable within a {{#each}} loop and a custom helper that will test the value of @index. Look at the snippet code below to suit your needs.
$(document).ready(function () {
var context = {
"items" : [{"name":"item1"},{"name":"item2"},{"name":"item3"},{"name":"item4"},{"name":"item5"},{"name":"item6"},{"name":"item7"},{"name":"item8"},{"name":"item9"},{"name":"item10"},{"name":"item11"},{"name":"item12"},{"name":"item13"}]
};
Handlebars.registerHelper('test', function(lvalue, operator, rvalue, options) {
var doDisplay = false;
var items = (""+rvalue).split("|");
var arrayLength = items.length;
for (var i = 0; (i < arrayLength); i++) {
if (operator == "eq") {
if (lvalue == items[i]) {
doDisplay = true;
}
} else if (operator == "ne") {
if (lvalue != items[i]) {
doDisplay = true;
}
} else if (operator == "gt") {
if (parseFloat(lvalue) > parseFloat(items[i])) {
doDisplay = true;
}
} else if (operator == "lt") {
if (parseFloat(lvalue) < parseFloat(items[i])) {
doDisplay = true;
}
}else if (operator == "le") {
if (parseFloat(lvalue) <= parseFloat(items[i])) {
doDisplay = true;
}
}else if (operator == "ge") {
if (parseFloat(lvalue) >= parseFloat(items[i])) {
doDisplay = true;
}
}
}
if (doDisplay) {
return options.fn(this);
} else {
return "";
}
});
var source = $("#sourceTemplate").html();
var template = Handlebars.compile(source);
var html = template(context);
$("#resultPlaceholder").html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="sourceTemplate" type="text/x-handlebars-template">
Complete list<br/>
<ul>
{{#each items}}
<li>
{{@index}} {{name}}
</li>
{{/each}}
</ul>
Partial list<br/>
<ul>
{{#each items}}
{{#test @index 'lt' 4}}
<li>
{{@index}} {{name}}
</li>
{{/test}}
{{/each}}
</ul>
</script>
<div id="resultPlaceholder">
</div>
这篇关于车把-不是每个而是一些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文