[英]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));
您可以使用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.