Access a variable outside the scope of a Handlebar

2019-01-08 04:10发布

问题:

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?

As always, thanks in advance.

回答1:

Try

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

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



回答2:

Or you can use absolute path like this:

<option value="{{id}}">{{title}} {{@root.user.path.to.externalValue}}</option>