假设我在传递给模板的结构中有两个数组:
{
days: 'Mon,Tue,Wed,Thu,Fri'.split(','),
times: 'Morning,Afternoon,Night'.split(',')
}
我想列出每一天,每天都列出一次。但是,当我在times
数组上的循环中引用days
数组时,似乎我认为我想要当前days
元素的成员。如何从循环内引用一个成员而不是另一个成员?
var theTemplate = Handlebars.compile(document.getElementById('example').innerHTML);
var data = {
days: 'Mon,Tue,Wed,Thu,Fri'.split(','),
times: 'Morning,Afternoon,Night'.split(',')
};
document.body.innerHTML += theTemplate(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
<script id="example" type="text/x-handlebars-template">
<ul>
{{#days}}
<li>
{{.}}
<ul>
{{#times}}
<li>{{.}}</li>
{{/times}}
</ul>
</li>
{{/days}}
</ul>
</script>
答案 0 :(得分:3)
您应该使用引用父模板范围的父路径段(../
):
var theTemplate = Handlebars.compile(document.getElementById('example').innerHTML);
var data = {
days: 'Mon,Tue,Wed,Thu,Fri'.split(','),
times: 'Morning,Afternoon,Night'.split(',')
};
document.body.innerHTML += theTemplate(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>
<script id="example" type="text/x-handlebars-template">
<ul>
{{#days}}
<li>
{{.}}
<ul>
{{#../times}}
<li>{{.}}</li>
{{/../times}}
</ul>
</li>
{{/days}}
</ul>
</script>