Reputation: 16253
I render a HTML select
with Handlebars, but I cannot set the selected value, if such value is itself already a rendered data attribute. I found other solutions in SO not satisfactory since they do not address this particular issue.
I tried
<select>
{{#each countriesList}}
<option value="{{@key}}" {{{isSelected ./setCountry @key}}}>
{{this}}
</option>
{{/each}}
</select>
I have the following helper
to try to set the selected value
isSelected: function (Country, key) {
return Country === key ? 'selected' : '';
}
I render in expressjs
var countries = {'en': 'England', 'fr': 'France', 'de' : 'Germany'};
var data = {'countriesList':countries, 'setCountry': 'fr'};
res.render('home', data);
It should have set the France option as the selected option, but it doesn't work! I also tried to get the rendered attribute from the helper function, but without success. Any ideas?
Upvotes: 2
Views: 3365
Reputation: 16253
I found the solution. Apparently it has to do with the dot. Instead of ./
it should be ../
to make reference to the main data variable. Now it works
<select>
{{#each countriesList}}
<option value="{{@key}}" {{{isSelected ../setCountry @key}}}>
{{this}}
</option>
{{/each}}
</select>
helper:
isSelected: function (Country, key) {
return Country === key ? 'selected' : '';
}
expressjs:
var countries = {'en': 'England', 'fr': 'France', 'de' : 'Germany'};
var data = {'countriesList':countries, 'setCountry': 'fr'};
res.render('home', data);
Upvotes: 4