jwl
jwl

Reputation: 10514

How to reference a variable outside the current block variable?

Say I have two arrays in a structure I'm passing to my template:

{
  days: 'Mon,Tue,Wed,Thu,Fri'.split(','),
  times: 'Morning,Afternoon,Night'.split(',')
}

I want to list each day, and for each day, list each time. However, when I reference the times array inside a loop over the days array, it seems to think I want a member of the current days element. How can I reference one member from inside a loop over another?

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>

Upvotes: 1

Views: 59

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44201

You should use a parent path segment (../), which references the parent template scope:

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>

Upvotes: 3

Related Questions