繁体   English   中英

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

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

在车把中,我需要检查一个对象是否为空,如果不是,那么我需要运行一个循环来从该对象中获取内容。 下面是我的代码和 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

您可以使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM