我需要为以下JSON代码添加一个包含4个图像的div:
var images = [
{img_path: "1/1.jpg"},
{img_path: "1/2.jpg"},
{img_path: "1/3.jpg"},
{img_path: "1/4.jpg"},
{img_path: "1/5.jpg"},
{img_path: "1/6.jpg"},
{img_path: "1/7.jpg"},
{img_path: "1/8.jpg"},
{img_path: "1/9.jpg"},
{img_path: "1/10.jpg"}
];
我的车把模板代码如下所示:
<script id="gallery-template" type="text/x-handlebars-template">
@{{#each images}}
@{{#compare @index '%' 4}}
<div class="outer">
{{/compare}}
<img src="@{{img_path}}" />
@{{#compare @index '%' 8}}
</div>
{{/compare}}
@{{/each}}
</script>
Handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) {
var operators, result;
if (arguments.length < 3) {
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
}
if (options === undefined) {
options = rvalue;
rvalue = operator;
operator = "===";
}
operators = {
'==': function (l, r) { return l == r; },
'===': function (l, r) { return l === r; },
'!=': function (l, r) { return l != r; },
'!==': function (l, r) { return l !== r; },
'<': function (l, r) { return l < r; },
'>': function (l, r) { return l > r; },
'<=': function (l, r) { return l <= r; },
'>=': function (l, r) { return l >= r; },
'typeof': function (l, r) { return typeof l == r; },
'%': function (l, r) { return l % r == 0; }
};
if (!operators[operator]) {
throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator);
}
result = operators[operator](lvalue, rvalue);
if (result) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
但我的第一个div创建逻辑看起来很好,但根据这个关闭div是我无法实现的。它应该精确地打破4,如果我有10,那么它应该关闭最后2,即4,4,2。如果需要实现这一点,我也可以更改JSON模式。
答案 0 :(得分:0)
我设法通过调整帮助和函数调用来做到这一点:
<script id="gallery-template" type="text/x-handlebars-template">
@{{#each images}}
@{{#compare @index '%' 4 @last}}
<div class="container">
@{{/compare}}
<img src="@{{img_path}}">
@{{#compare @index '!%' 4 @last}}
</div>
@{{/compare}}
@{{/each}}
</script>
通过添加额外的运算符!%并将 lastval 传递给辅助函数
'!%': function (l, r) {
if(islast === true)
return true; l= l+1;
return l % r == 0;
}