2012-04-15 29 views
4

在meteor.com上的基本排行榜示例中,有一個名爲selected_name的方法。打開meteor方法,將單個對象返回到句柄的上下文中

Template.leaderboard.selected_name = function() { 
    var player = Players.findOne(Session.get("selected_player")); 
    return player && player.name; 
    }; 

    {{#if selected_name}} 
    <div class="details"> 
    <div class="name">{{selected_name}}</div> 
    <input type="button" class="inc" value="Give 5 points" /> 
    </div> 
    {{/if}} 

相反,我想返回整個播放器對象,然後通過把手將該對象視爲上下文。我希望我可以這樣說:

Template.leaderboard.selected_person = function() { 
    var player = Players.findOne(Session.get("selected_player")); 
    return player || false; 
    }; 

    {{#if selected_person}} 
    <div class="details"> 
    <div class="name">{{name}}</div> 
    <input type="button" class="inc" value="Give 5 points" /> 
    </div> 
    {{/if}} 

上面的#if代碼塊實際上並不適用於流星。 #if語句只是對selected_person方法進行評估,嵌套的{{name}}完全沒有。我想知道是否可以編寫一個方法,以便返回的對象可以用作#if塊的上下文。

回答

7

解決!如果我只是使用#with而不是#if,那麼一切都很好。因爲它說在車把文檔You can shift the context for a section of a template by using the built-in with block helper.

{{#if selected_person}} 
    {{#with selected_person}} 
    <div class="details"> 
    <div class="name">{{name}}</div> 
    <input type="button" class="inc" value="Give 5 points" /> 
    </div> 
    {{/with}} 
    {{/if}} 

如果/有相當繁瑣,顯然是不值得的,只用於呈現的名字,但我能想到的時間爲一個對象的多個屬性,其中特別呈現的嵌套會很有用。

+0

if語句似乎並不需要,看起來像在我自己​​所期望的自己的句柄上。 – jonathanKingston 2012-04-15 14:31:37

+0

@jonathanKingston在沒有選定的人的情況下,它會渲染其餘的div,這可能不是你想要的。在我的使用案例中,我絕對只想要片段呈現,如果有值的話。 – Benson 2012-04-15 21:22:51

+1

或者,將if和the結合成一個助手。例如:'Handlebars.registerHelper('ifwith',function(context,options){if}(context)return options.fn(context); });'。這樣,selected_person只被調用一次,而不是一次因爲if和因爲with而一次。 – 2012-05-30 03:37:50

0

我做了類似的事情,但我不認爲這是「正確的方式」?

Template.leaderboard.selected_person = function() { 
    return Players.find(Session.get("selected_player")); 
}; 

{{#each selected_person}} 
<div class="details"> 
    <div class="name">{{name}}</div> 
    <input type="button" class="inc" value="Give 5 points" /> 
</div> 
{{/each}} 
+0

我也做過類似的事情,直到我找到lashleigh關於使用#with的答案。奇蹟般有效。 :-) – Benson 2012-04-15 21:19:56