Sub*_*ash 25 html jquery handlebars.js
我写了一个显示推文的小插件.以下是循环和显示推文的代码.
<script id="tweets-template" type="text/x-handlebars-template" >
{{#each this}}
<li>
<p>{{tweet}}</p>
<span id="author">{{author}}<span/>
</li>
{{/each}}
</script>
Run Code Online (Sandbox Code Playgroud)
但我想要做的是将推文的数量限制为5或10.但循环列出了所有可用的推文.如何限制for循环中的推文.喜欢
for(i=0;i<5;i++){display the tweets}
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 39
我想你有两个选择:
实际的each实现非常简单,因此将其调整为包含上限非常简单:
// Warning: untested code
Handlebars.registerHelper('each_upto', function(ary, max, options) {
if(!ary || ary.length == 0)
return options.inverse(this);
var result = [ ];
for(var i = 0; i < max && i < ary.length; ++i)
result.push(options.fn(ary[i]));
return result.join('');
});
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中:
<script id="tweets-template" type="text/x-handlebars-template" >
{{#each_upto this 5}}
<li>
<p>{{tweet}}</p>
<span id="author">{{author}}<span/>
</li>
{{/each_upto}}
</script>
Run Code Online (Sandbox Code Playgroud)
tal*_*kol 20
Dtipson说each,我同意复制目前不是一个好主意.
他提出的limit帮助方法确实是IMO的最佳方式,这里是实现它所需的代码:
// limit an array to a maximum of elements (from the start)
Handlebars.registerHelper('limit', function (arr, limit) {
if (!Array.isArray(arr)) { return []; }
return arr.slice(0, limit);
});
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中(假设你的数组是cart.products):
{{#each (limit cart.products 5)}}
<li>Index is {{@index}} - element is {{this}}</li>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
你需要一个支持子表达式的最新把手版本当然可以工作.
| 归档时间: |
|
| 查看次数: |
15109 次 |
| 最近记录: |