2015-04-30 117 views
1

模板把手内环路助手

<script id='handlebar-template'> 
    {{#each tags}} 
      {{#isObject this}} 
       <span>Object</span> 
      {{else}} 
       <span>String</span> 
      {{/isObject}} 
    {{/each}} 
    </script> 

脚本

<script> 
    Handlebars.registerHelper('isObject', function(o) { 
     return typeof o === "object"; 
    }); 

    var props = {"tags": ["Google"]} 
    var html = $("#handlebar-template").html(); 
    var template = Handlebars.compile(html); 
    console.log(template(props)); 
</script> 

总产值有望

<span>String</span> 

实际输出

false 

else块被执行,但输出返回是false代替<span>String</span>

回答

1

您正在使用助手错误或有一个错误的帮手。

在第一种情况下,变更模板使用{{#if}}帮手:

{{#if (isObject this)}} 
    <span>Object</span> 
{{else}} 
    <span>String</span> 
{{/if}} 

看这个fiddle

在第二种情况下,您需要在帮助程序中自己实现{{else}}逻辑。
看看Handlebars块帮助文档conditionals