我正在了解 Handlebars.js,我想向社区提问。我知道我还有很多东西要学,而且我正在路上,但我想看看这个问题的例子。
在 JS 中使用对象创建的数组:
var data =
[
{
Field: "id",
Type: "int(11)",
Null: "NO",
Key: "PRI",
Default: null,
Extra: "auto_increment"
},
{
Field: "id2",
Type: "int(131)",
Null: "N3O",
Key: "PR3I",
Default: null,
Extra: "auto_increment"
}
];
之所以采用这种格式,是因为我从服务器接收到的 JSON 看起来就是这样,但现在为了测试我不想进行 ajax 调用。
模板:
<table>
<thead>
<tr>
{{#each this}}
{{#only_once this}}
{{#key_value this}}
<th>{{key}}</th>
{{/key_value }}
{{/only_once}}
{{/each}}
</tr>
</thead>
...
因为对象在一个数组中,我必须首先使用 {{#each}}
循环数组然后有一个注册的助手(我在 github 上找到)帮助我获得 key 因为我只想将它们写入 thead。
没有我的 if 语句它工作正常,用键填充 thead,但是因为有 2 个对象,它打印出两次名称。
我的问题是我只想打印一次,如果检查数组的索引是否大于 0 以停止打印数据,if 将解决我的问题,但是..
.. Handlebars 不支持条件语句,因此像{{#if x > y}}
这样的代码是不可能的。你们认为最好的解决方案是什么?
Handlebars.registerHelper("only_once", function(item, fn){
var buffer;
var i = 0;
if (i > 0) {
buffer = false;
}
i++;
return buffer;
});
好吧,我试着写了一个助手,但我觉得我做错了什么。我的理论是,如果模板中的“this
”(我认为)指向数组,然后增加 i
以检查是否数组的索引> 0,最后如果它是真的而不是发回假 - 所以我认为它会告诉如果不运行里面的代码,但我错了。
最佳答案
如 this other SO answer 中所述正如@SimonBoudrias 在他的回答中提到的那样,由于 Handlebars 1.1.0,{{@first}}
由 {{#each}} 原生支持
助手。
因此,您可以打印数组中第一个对象的所有属性名称,方法是仅使用 handlebars native 帮助程序,如下所示:
{{#each array}}
{{#if {{@first}}}}
<!-- It is the first object on the array, print the key for each attribute -->
{{#each this}}
<th>{{@key}}</th>
{{/each}}
{{/if}}
{{/each}}
关于向 Handlebars 添加条件 if 语句的附加说明:
Handlebars 是一个无逻辑模板系统,因此它不包含逻辑语句。
不过,如果您想使用模板和 Handlebars 来完成它,您可以通过编写一个帮助程序来解决这个问题,如本 SO answer 中所解释的那样.在您的情况下,助手可能是这样的:
Handlebars.registerHelper('ifIsZero', function(value, options) {
if(value === 0) {
return options.fn(this);
}
return options.inverse(this);
});
然后,您可以在您的模板中调用它,仅当索引等于 0 时才执行某些操作:
{{#each array}}
{{#ifIsZero {{@index}}}}
<!-- @index is equal to 0, do something -->
<!-- eg. print the key for each attribute of the object using {{@key}} -->
{{#each object}}
<th>{{@key}}</th>
{{/each}}
{{else}}
<!-- otherwise, do something else -->
{{/ifIsZero}}
{{/each}}
关于javascript - Handlebars 的 if 语句中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094459/