如何在 Handlebars 的 if 语句中检查对象是否为空?

4
在handlebars中,我需要检查一个对象是否为空,如果不是,则需要运行循环来获取对象的内容。以下是我的代码和codepen链接。我想这很简单,但似乎什么都不起作用。我原本认为handlebars的#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个回答

3
您可以使用内置的handlebars 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>


谢谢你的建议,但我已经在使用each了。我的标记部分需要存在于each之外。这意味着我必须使用两个each,如果有数据,则显示比我需要的更多的标记。因此,我确实需要一个if或自定义helper。http://codepen.io/matt3224/pen/gaKyKv?editors=101 - mattpilott
你只需要在对象为空的情况下隐藏类吗?如果是这样,你可以将 class="..." 包裹在 if 帮助器中。如果不是,请在问题中给出一个例子,说明你期望空对象和非空对象情况下的标记结果分别是什么样的。 - Nick Bartlett
嗨,Nick,有没有办法在不使用each helper的情况下检查对象是否为空?我不能像你展示的那样使用each helper的原因是我有一个包装器,如果对象为空,我不想输出它。请检查最新的codepen,您应该能够从标记中看到我的问题。我也会添加一些注释。非常感谢您的帮助。 - mattpilott
2
很不幸,我认为在Handlebars中没有简单的方法来解决这个问题。因为if/unless helpers和with helper都将{}{a: "test"}视为“true”。你可以选择:1)创建一个自定义helper;或2)使用别人已经构建的helper,例如http://assemble.io/helpers/helpers-collections.html#-empty-。但是我认为仅使用核心handlebars库是不可能实现这一点的。如果对象不存在,而不是存在且为空,那么这将容易得多。 - Nick Bartlett

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接