如何引用当前块变量之外的变量?

时间:2015-05-15 14:53:23

标签: javascript mustache handlebars.js

假设我在传递给模板的结构中有两个数组:

{
  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>

1 个答案:

答案 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>