Search code examples
meteormeteor-blaze

Conditionally mark a checkbox as checked in Meteor using Blaze


I'm not entirely sure what's wrong here, or how I'm supposed to approach it differently - but googling just brings up references to 'isChecked' - something I'm not using.

I just want to flag a checkbox as checked if the associated field value is present:

<input type="checkbox" name="services.bananaExports" {{ #if currentUser.profile.services.bananaExports }} checked {{ /if }} />

But I'm getting:

Reactive HTML attributes must either have a constant name or consist of a single {{helper}} providing a dictionary of names and values. A template tag of type BLOCKOPEN is not allowed here.

Honestly I'm not sure what that's trying to tell me, I'm new to meteor/blaze but it's a pretty basic if clause? Can I not issue an if statement here? If not how would I approach this?


Solution

  • The best solution I can think of is to define a helper like this one:

    Template.registerHelper('isTruthy', function(varName) {
      return !!varName;
    });
    

    Then you can do things like this:

    {{#each foodList}}
      {{foodName}} <input type="checkbox" checked={{isTruthy eaten}}>
    {{/each}}
    

    Of course, in your case:

    <input type="checkbox" name="services.bananaExports" checked={{isTruthy currentUser.profile.services.bananaExports}}>