I'm using the following helper to allow me to do conditional comparisons:
Handlebars.registerHelper("ifCond", function (v1, operator, v2, options) {
switch (operator) {
case "==":
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case "===":
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case "<":
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case "<=":
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case ">":
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case ">=":
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
Then I have my template setup like this:
<select name="mode">
{{#each data.modes}}
<option {{#ifCond data.curmode '==' this}} selected="selected" {{/ifCond}} value="{{this}}">{{this}}</option>
{{/each}}
</select>
I'm passing in data
which is an object containing modes
(a flat array of modes available, strings) and curmode
which is a string containing the currently selected mode.
As far as I can tell everything is being passed in fine - I can display the data.curmode
and each of the data.modes
populates correctly. However, it's not outputting the selected="selected"
on match.
When you use an iterator, such as #each
, everything inside the block is referenced with respect to the current element. So, if you say this:
{{#each a}}
{{x}}
{{/each}}
Handlebars will look for x
within the current value of a
rather than in the global namespace for the template. So you need to look outside the {{#each data.modes}}
value if you want to get at the top level data.curmode
:
<select name="mode">
{{#each data.modes}}
<option {{#ifCond ../data.curmode '==' this}} ...
{{/each}}
</select>
The ../
steps you up one level.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.