Search code examples
meteorternary-operatormeteoritespacebars

Ternary operators in Meteor


I am using Meteoris for working on my application. I have this scenario in forms. This is an edit view and I am just showing two of the 17 fields I have here:

<label for="name" class="control-label">Name *</label>
<input type="text" id="name" value="{{profile.name}}" placeholder="Name" class="form-control">
<label for="acctType" class="control-label">Account Type</label>
<select id="acctType" placeholder="Name" class="form-control">
    <option></option>
    <option value="1" {{(profile.acctType == 1) ? 'selected="selected"' : ""}}>Free</option>
    <option value="2" {{(profile.acctType == 2) ? 'selected="selected"' : ""}}>Paid</option>
</select>

I have a Name field and an Account Type field. For the Account Type, I have numeric values stored in the Mongo DB. When I try to check something like this, Okay, I am a PHP Developer, and in PHP I do this:

<label for="name" class="control-label">Name *</label>
<input type="text" id="name" value="<?php echo $profile_name; ?>" placeholder="Name" class="form-control">
<label for="acctType" class="control-label">Account Type</label>
<select id="acctType" placeholder="Name" class="form-control">
    <option></option>
    <option value="1"<?php echo ($profile_acctType == 1) ? ' selected="selected"' : ""; ?>>Free</option>
    <option value="2"<?php echo ($profile_acctType == 2) ? ' selected="selected"' : ""; ?>>Paid</option>
</select>

I was getting the following errors. When I didn't give any spaces between " and {, I was getting:

While building the application:
client/views/users/profile.html:42: Expected space
...    <option value="1"{{(profile.acctType ...

And when I tried giving a space, I got this error:

While building the application:
client/views/users/profile.html:42: Expected IDENTIFIER
... <option value="1" {{(profile.acctType ==...

What is your advice on fixing this issue?


Solution

  • With more info about your end goal I could make something more eloquent, but here's an option

    Template.blah.helpers({
        isAccountType: function (acctType) {
            if (user.profile.acctType === acctType) return 'selected'
        }
    });
    <option value="1" {{isAccountType 1}}>Free</option>