Access a variable outside the scope of a Handlebars.js each loop

lucke84 picture lucke84 · Nov 30, 2012 · Viewed 53.5k times · Source

I have a handlebars.js template, just like this:

{{externalValue}}

<select name="test">
    {{#each myCollection}}
       <option value="{{id}}">{{title}} {{externalValue}}</option>
    {{/each}}
</select>

And this is the generated output:

myExternalValue

<select name="test">
       <option value="1">First element </option>
       <option value="2">Second element </option>
       <option value="3">Third element </option>
</select>

As expected, I can access the id and title fields of every element of myCollection to generate my select. And outside the select, my externalValue variable is correctly printed ("myExternalValue").

Unfortunately, in options' texts, externalValue value is never printed out.

My question is: how can I access a variable outside the scope of the handlebars.js each from within the loop?

Answer

spliter picture spliter · Nov 30, 2012

Try

<option value="{{id}}">{{title}} {{../externalValue}}</option>

The ../ path segment references the parent template scope that should be what you want.