我有在车把js处理if条件的问题
{"lstModel":[{"name":"Sizes","values":[{"value":"L"},{"value":"XL"},{"value":"M"}]},{"name":"Colours","values":[{"value":"Green"}]}]}
<script type="text/x-handlebars-template" id="filter">
<form class="col-md-6" id="filter-{{name}}">
<label>Select {{name}}</label>
{{#if name.Sizes}}
<div class="size-selector">
{{#values}}
<div class="entry">{{value}}</div>
{{/values}}
</div>
{{else if name.Colours}}
<div class="color-selector">
{{#values}}
<div class="entry" data-value={{value}} style="background: {{value}};"> </div>
{{/values}}
</div>
{{/if}}
</form></script>
我面临的问题是当我试图检查json的值时,如果条件不显示在条件内。请帮忙。
答案 0 :(得分:0)
您的模板应该像下面一样重写,以使条件和循环正常工作
<script type="text/x-handlebars-template" id="filter">
{{#each lstModel}}
<form class="col-md-6" id="filter-{{name}}">
<label>Select {{name}}</label>
{{#ifCond name 'Sizes'}}
<div class="size-selector">
{{#each values}}
<div class="entry">{{value}}</div>
{{/each}}
</div>
{{else}}
{{#ifCond name 'Colours'}}
<div class="color-selector">
{{#each values}}
<div class="entry" data-value={{value}} style="background: {{value}};"> </div>
{{/each}}
</div>
{{/ifCond}}
{{/ifCond}}
</form>
{{/each}}
</script>
你需要注册一个自定义的把手帮手&#39; ifCond
匹配特定字符串。
Handlebars.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
最后,输出(编译后的HTML)将如下所示,
<script type="text/x-handlebars-template" id="filter">
<form class="col-md-6" id="filter-Sizes">
<label>Select Sizes</label>
<div class="size-selector">
<div class="entry">L</div>
<div class="entry">XL</div>
<div class="entry">M</div>
</div>
</form>
<form class="col-md-6" id="filter-Colours">
<label>Select Colours</label>
<div class="color-selector">
<div class="entry" data-value=Green style="background: Green;"> </div>
</div>
</form>
</script>
希望这有帮助。