限制每个handlebars.js的结果 [英] limit results of each in handlebars.js
本文介绍了限制每个handlebars.js的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个显示推文的小插件。以下是循环显示推文的代码。
< script id =tweets-templatetype =text / x-handlebars-template>
{{#each this}}
< li>
< p> {{tweet}}< / p>
< span id =author> {{author}}< span />
< / li>
{{/ each}}
< / script>
但我想要做的是将推文的数量限制为5或10。列出所有可用的推文。如何限制在for循环中的推文。像
for(i = 0; i <5; i ++){显示推文}
解决方案
我认为您有两个选择:
实际 每个
实现非常简单,因此调整它以包含上限是非常简单的:
//警告:未经测试的代码
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('');
} ) ;
然后在您的模板中:
< script id =tweets-templatetype =text / x-handlebars-template>
{{#each_upto this 5}}
< li>
< p> {{tweet}}< / p>
< span id =author> {{author}}< span />
< / li>
{{/ each_upto}}
< / script>
I have written a small plugin that displays tweets. following is the code that loops and displays the tweets.
<script id="tweets-template" type="text/x-handlebars-template" >
{{#each this}}
<li>
<p>{{tweet}}</p>
<span id="author">{{author}}<span/>
</li>
{{/each}}
</script>
But what I want to do is limit the number of tweets to 5 or 10. But the loop is listing all the available tweets. How do I limit the tweets like in for loop. like
for(i=0;i<5;i++){display the tweets}
解决方案
I think you have two options:
- Limit the size of your collection before handing it to Handlebars.
- Write your own block helper that lets you specify a limit.
The actual each
implementation is pretty simple so adapting it to include an upper limit is fairly straight forward:
// 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('');
});
Then in your template:
<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>
这篇关于限制每个handlebars.js的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文