I am trying to do what I think should be a very simple task, but have been failing to do so in the past hour. I want to select a select option by default if the user property matches the value.
<select name="myName">
{{#each addKeys myTable}} <!-- addKeys creates variables for keys and values -->
<option value="{{key}}" {{#if currentUser.property === key}}selected="selected"{{/if}}>{{value}}</option>
{{/each}}
</select>
Now I thought this was straightforward enough to be implemented. But it turns out that Spacebars do not allow conditional operators other than the negation exclamation mark, so equal signs are out of question. I then tried something horrible for the sake of trying:
In template myTemplate
:
<select name="myName">
{{#each addKeys myTable}}
<option value="{{key}}" {{isSelected currentUser.property key}}>{{value}}</option>
{{/each}}
</select>
In mytemplate.js
:
Template.myTemplate.helpers({
isSelected: function(v1, v2) {
if (v1 === v2)
return "selected=\"selected\"";
return '';
}
});
Not only is this code terrible, terrible to look at, it does not work:
Exception in Meteor UI: String contains an invalid character
I don't understand why something that simple seems so impossible to achieve. Am I missing something there?
Try this:
In your template:
<option value={{key}} selected={{isSelected currentUser.property key}}>
Then have your helper return a boolean.
More on the topic here: https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected