Search code examples
meteorspacebars

'Or' condition in Meteor.js template blocks


Is there a way to do a conditional "and" or "or" in a Meteor template? What I am trying to do is something like this:

{{#if isInRole 'ADMIN' || isInRole 'INSPECTOR'}}
  ...do some stuff
{{/if}}

using helpers provided by a 3rd party package alanning:roles. This seems to have come up multiple times in my coding with Meteor and I can and have worked around it, usually by duplication of the block code, but it would be really nice if there already existed some way to handle an OR or AND condition without crazy gyrations.


Solution

  • Meteor using spacebar which is based on handlebars. In handlebars, there are now direct way for logical operators.

    You can do small workaround to handle the or by creating a Template.helper

    Template.registerHelper("equals_or", function(param, arr) {
       arr = arr.split(",");
       if (arr.indexOf(param) !== -1) {
          return true;
       } 
       else {
         return false;
       }
    });
    

    Then in the HTML you can do

    {{#if equals_or isRole "ADMIN,INSPECTOR"}}
      ...do some stuff
    {{else}}
       ...do some other stuff
    {{/if}}
    

    I might not be a perfect solution, but it is doing the job.

    Check this answer too.