使用Handlebars,为{{#each ...}}
帮助器呈现的每个元素添加一个或另一个类的最简单方法是什么?我必须与站点的现有CSS设置集成,这需要在列表中的交替元素中添加一个或另一个类。
帮助示例:
{{#each items}}
<div class="{{what here?}}">...</div>
{{/each}
...我们希望even
或odd
作为班级名称。 (是的,再次,我知道这可以通过CSS完成;我正在与现有的网站的CSS集成,后者使用交替的类。)
答案 0 :(得分:1)
作为Handlebars的新手,我没有看到任何内置的东西,但API可以很容易地添加一个帮助程序,让您从任意长度的项目列表中进行选择,如下所示:
Handlebars.registerHelper('cycle', function(index) {
index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
return arguments[index + 1];
});
使用它将是:
{{#each items}}
<div class="{{cycle @index 'even' 'odd'}}">...</div>
{{/each}
Handlebars.registerHelper('cycle', function(index) {
index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
return arguments[index + 1];
});
var items = [
"one", "two", "three", "four", "five"
];
var template = Handlebars.compile(
document.getElementById("template").innerHTML
);
var html = template({items: items});
document.body.insertAdjacentHTML(
"beforeend",
html
);
.even {
color: blue;
}
.odd {
color: green;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
{{#each items}}
<div class="{{cycle @index 'even' 'odd'}}">{{this}}</div>
{{/each}}
</script>
或者如果我想要轮换三个类:
{{#each items}}
<div class="{{cycle @index 'one' 'two' 'three'}}">...</div>
{{/each}
Handlebars.registerHelper('cycle', function(index) {
index = index % (arguments.length - 2); // -2 to leave out `index` and the final argument HB adds
return arguments[index + 1];
});
var items = [
"one", "two", "three", "four", "five"
];
var template = Handlebars.compile(
document.getElementById("template").innerHTML
);
var html = template({items: items});
document.body.insertAdjacentHTML(
"beforeend",
html
);
.one {
color: blue;
}
.two {
color: green;
}
.three {
color: red;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
{{#each items}}
<div class="{{cycle @index 'one' 'two' 'three'}}">{{this}}</div>
{{/each}}
</script>