如果我有以下json:
{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
}
我想将所有json字段输出到HTML中:
<div>
{{#each this}}
<p>{{@key}} - {{this}}</p>
{{/each}}
</div>
这将输出以下内容:
<div>
<p>a - 1</p>
<p>b - 2</p>
<p>c - 3</p>
<p>d - 4</p>
<p>e - 5</p>
</div>
但是,如何使用此循环从迭代中排除字段c
:
<div>
{{#each this}}
{{#if key does not equal 'c'}}
<p>{{@key}} - {{this}}</p>
{{#if key does not equal 'c'}}
{{/each}}
</div>
输出为:
<div>
<p>a - 1</p>
<p>b - 2</p>
<p>d - 4</p>
<p>e - 5</p>
</div>
如何使用Handlebars.js实现这一目标?
答案 0 :(得分:1)
您可以设置自定义帮助程序,以便在条件为false时返回true
var data = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
};
var source = $("#entry-template").html();
Handlebars.registerHelper("notEqual", function(target, condition, options) {
if (target !== condition) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
var tempalte = Handlebars.compile(source);
$("body").append(tempalte(data));
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
<div>
{{#each this}}
{{#notEqual @key 'c'}}
<p>{{@key}} - {{this}}</p>
{{/notEqual}}
{{/each}}
</div>
</script>