【发布时间】:2016-05-14 15:15:59
【问题描述】:
我需要为以下 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 模式。
【问题讨论】:
标签: javascript json algorithm handlebars.js helper