我试图使用Handlebars创建术语表。每个术语都包含一系列相关术语。如果我尝试使用{{ #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 :(得分: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>