2012-08-08 76 views
3

如何在車把模板中創建模板?
那是我的模板:模板內的車把模板

<script type="text/x-handlebars-template" id="animal-template"> 
    <div class="locationSelect"> 
    {{content}} 
    </div> 
</script> 
<script type="text/x-handlebars-template" id="cat-template"> 
    <div> 
    I am cat 
    </div> 
</script> 
<script type="text/x-handlebars-template" id="dog-template"> 
    <div> 
    I am dog 
    </div> 
</script> 

我想在動物模板中運行(CAT-模板或狗模板)加載撥款模板。我怎樣才能做到這一點?

回答

7

局部模板來當你需要在幾個不同的環境下使用一個Handlebars.js模板時,這個功能很方便

<script id="people-template" type="text/x-handlebars-template"> 
    {{#each people}} 
    {{> person}} 
    {{/each}} 
</script> 

<script id="person-partial" type="text/x-handlebars-template"> 
    <div class="person"> 
    <h2>{{first_name}} {{last_name}}</h2> 
    <div class="phone">{{phone}}</div> 
    <div class="email"><a href="mailto:{{email}}">{{email}}</a></div> 
    <div class="since">User since {{member_since}}</div> 
    </div> 
</script> 

<script type="text/javascript"> 
    $(document).ready(function() { 
    var template = Handlebars.compile($("#people-template").html()); 
    Handlebars.registerPartial("person", $("#person-partial").html()); 

    template(yourData); 
    } 
</script> 

http://blog.teamtreehouse.com/handlebars-js-part-2-partials-and-helpers

+0

我們通常不會在這裏鏈接「僅鏈接」答案,但您提供的不僅僅是鏈接。可能這是關於「最簡單」的有效答案,即FYI。歡迎! – 2013-12-19 00:50:20

2

您可以根據所呈現的項目計算templateName的項目視圖屬性:

App.AnimalView = Ember.View.extend({ 
    templateNameBinding: function() { 
    var kind = this.get('animal.kind'); 
    return '%@-template'.fmt(kind); 
    }.property('animal.kind') 
}); 

然後在容器模板,通過他們的觀點呈現的項目:

<script type="text/x-handlebars-template" id="animal-template"> 
    <div class="locationSelect"> 
    {{#for animal in content}} 
    {{view App.AnimalView animalBinding="animal"}} 
    {{/for}} 
    </div> 
</script> 
+1

其實我要尋找一個解決方案,因爲我做了這個的jQuery插件,不依賴於灰燼。 – Naor 2012-08-09 08:15:41

+2

在這種情況下,你不應該把你的問題標記爲[tag:ember.js] ... :-) – 2012-08-09 08:24:27

+0

我認爲Ember.js用戶可能知道如何解決它沒有燼。:)我將刪除燼標籤。 – Naor 2012-08-09 11:01:32