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

扶醉桌前 提交于 2019-11-26 11:48:54

问题


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?


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


来源:https://stackoverflow.com/questions/13645084/access-a-variable-outside-the-scope-of-a-handlebars-js-each-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!