我如何使用Handlebars.js创建条件行类?
[英] How can I create conditional row classes using Handlebars.js?
本文介绍了我如何使用Handlebars.js创建条件行类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< ul class =row>我有一个布局,其结构如下
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< / ul>
我想要的是,对于每个第5个项目,都会创建一个新行,行,这样我的代码可以如下所示:
< ul class =row>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< li>内容< / li>
< / ul>
< ul class =row>
< li>内容< / li>
< li>内容< / li>
< / ul>
任何人都可以建议如何使用handlebars助手完成这项工作吗?
class =lang-js prettyprint-override> // attr:要拆分的当前上下文中属性的名称,
//将被转发给后代
/ / count:组中元素的数量
// opts:Handlebar给出的参数,opts.fn是块模板
Handlebars.registerHelper('splitter',function(attr,count,opts){
var context,result,arr,i,zones,inject;
context = this;
arr = context [attr];
zones = Math.ceil( (i = 0; i< zones; i ++){
inject = {}; $ b $($ arg.length / count);
result =;
b注射[attr] = arr.slice(i * count,(i + 1)* count);
result + = opt s.fn(注射);
}
返回结果;
});
假设您的数据以 {rows:[{text:Row 1},...]}
,一个模板可能看起来像这样
{{#splitterrows5}}
< ul class ='row'>
{{#each rows}}
< li> {{text}}< / li>
{{/ each}}
< / ul>
{{/ splitter}}
和小提琴一起玩 http://jsfiddle.net/HwJ6s/
I Have a layout which is effectively structured as below
<ul class="row">
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
</ul>
What i would like is that for every 5th item a new row to be created with a class of "row" so that my code can look as shown below
<ul class="row">
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
<li>content</li>
</ul>
<ul class="row">
<li>content</li>
<li>content</li>
</ul>
Can anyone advise how this could be accomplished using a handlebars helper?
解决方案
You could create a wrapping helper that splits the array of rows in the desired number of elements:
// attr : name of the attribute in the current context to be split,
// will be forwarded to the descendants
// count : number of elements in a group
// opts : parameter given by Handlebar, opts.fn is the block template
Handlebars.registerHelper('splitter', function (attr, count, opts) {
var context, result, arr, i, zones, inject;
context = this;
arr = context[attr];
zones = Math.ceil(arr.length / count);
result="";
for (i = 0; i < zones; i++) {
inject = {};
inject[attr] = arr.slice(i * count, (i + 1) * count);
result += opts.fn(inject);
}
return result;
});
Assuming your data is passed as { rows: [ {text: "Row 1"}, ... ] }
, a template could look like this
{{#splitter "rows" 5}}
<ul class='row'>
{{#each rows}}
<li>{{text}}</li>
{{/each}}
</ul>
{{/splitter}}
And a Fiddle to play with http://jsfiddle.net/HwJ6s/
这篇关于我如何使用Handlebars.js创建条件行类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!