如果声明,如何检查手柄中的对象是否为空?

时间:2015-11-01 15:35:49

标签: javascript loops if-statement handlebars.js

在把手中,我需要检查一个对象是否为空,如果它不是,那么我需要运行一个循环来从对象中获取内容。下面是我的代码和codepen的链接。我想这很简单,但似乎没什么用。我原以为把手#if语句会看到一个空对象为未定义或0,最终条件将无法实现。

<div class="temp"></div>

<script id="temp" type="x-handlebars-template">
    {{#if tabs}}
    <p>true</p>
    {{/if}}
</script>

var template = Handlebars.compile($("#temp").html());

var tabs = {};

var context = {
    tabs: tabs
}

$('.temp').html(template(context));

http://codepen.io/matt3224/pen/gaKyKv?editors=101

1 个答案:

答案 0 :(得分:1)

您可以使用内置的把手each助手来完成您正在寻找的东西,甚至可以使用空对象有条件地渲染某些内容:

var template = Handlebars.compile($("#temp").html());

var tabs = {},
    test = {a: "Resources", b: "Contact"};

var context = {
    tabs: tabs,
    test: test
}

$('.temp').html(template(context));
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.0/handlebars.min.js"></script>

<div class="temp"></div>

<script id="temp" type="x-handlebars-template">
    <h3>each helper on empty object</h3>
    {{#each tabs}}
        <p>Key: {{@key}} Value = {{this}}</p>
    {{else}}
        <p>Your tabs object is empty!</p>
    {{/each}}
    
    <h3>each helper on non-empty object</h3>
    {{#each test}}
        <p>Key: {{@key}} Value = {{this}}</p>
    {{else}}
        <p>Your test object is empty!</p>
    {{/each}}
</script>

相关问题