2015-11-01 55 views
1

在句柄中,我需要檢查一個對象是否爲空,如果不是,那麼我需要運行一個循環來抓取對象中的內容。以下是我的代碼和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

你可以只使用內置的把手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>

+0

謝謝你,但我已經使用每一個,我的標記的一部分需要exi st在每個之外。這意味着我不得不使用2個,其中,如果數據顯示比我需要更多的標記。所以我確實需要一個if或者定製的幫手。 http://codepen.io/matt3224/pen/gaKyKv?editors=101 – matt3224

+0

這只是你需要隱藏類,如果對象是空的?如果是這樣的話,你可以在'if'助手中包裝那個'class =「...」''。如果不是的話,你可以舉一個例子來說明你期望得到的標記在空對象和非空對象情況下看起來像個別的樣子嗎? –

+0

嗨,尼克,無論如何檢查如果一個對象是空的,而不使用每個助手?我不能僅僅使用每個幫助器的原因是因爲我有一個包裝器,如果對象爲空,我不想輸出。檢查最新的codepen,你應該能夠從標記中看到我的問題。我也會添加一些評論。我非常感謝你對此的幫助。 – matt3224