2015-05-14 45 views
0

我正在嘗試使用把手來創建術語表。每個術語包含一系列相關術語。如果我嘗試使用{{ #each }}樣式語法,則會出現錯誤。如果我只使用{{ related }}它將數組中的每個項目轉換爲一個字符串。我需要逐個獲取每個元素,以便我可以將其包裝在一個樣式類的跨度中。把手:使用嵌套迭代器編譯模板

數據:

[ 
    { 
    "name": "Habitat", 
    "description": "The place in nature with distinct features (such as short grass, wet ground, dry rocks, etc.) that an animal calls home because it provides what it needs to survive: food, water and shelter.", 
    "related": ["range", "habitat fragmentation"] 
    }, 
    { 
    "name": "Habitat fragmentation", 
    "description": "When an animal’s homeland or range is split up into smaller pieces. <br><br>For example, if we place a road in the middle of a large field, we have fragmented the field into two pieces. If any animal’s den is on one side of the road and its food is on the other, the animal must now take the risk of crossing the road in order to survive.", 
    "related": ["habitat"] 
    } 
] 

模板

<script id="glossary-template" type="x-handlebars-template"> 
    {{#each .}} 
    <li class="term"> 
    <h3>{{ name }} {{ acronym }}</h3> 
    <p>{{{ description }}}</p> 
    <p>Related Terms:{{ #related }}<span class="tag">{{this}}<span>{{ /related }} 
    </li> 
    {{/each}} 
</script> 

回答

0

我覺得這裏的問題是,我是用兩個未命名的迭代器。我將數據作爲命名參數傳遞給編譯模板,現在一切正常。

$('ul').append(template({"terms": data})); 


<script id="glossary-template" type="x-handlebars-template"> 
    {{#terms}} 
    <li class="term"> 
    <h3>{{ name }} {{ acronym }}</h3> 
    <p>{{{ description }}}</p> 
    {{#related}}<span class="tag">{{this}}</span>{{/related}} 
    </li> 
    {{/terms}} 
</script> 
+0

如果這回答了您的問題,那麼請接受它作爲答案。 –