如何检查车把中的物体是否为空if语句

How to check whether object is empty in handlebars if statement?

本文关键字:是否 语句 if 何检查 检查      更新时间:2023-09-26

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

您只需使用内置的手把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>