a blog for those who code

Tuesday 19 July 2016

How to do conditional comparison in Handlebars

In this post we will be discussing about doing conditional comparison in Handlebars. Handlebars provides the power necessary to let you build semantic templates effectively with no frustration but there is always a question that how to do conditional comparison in Handlebars. Handlebars nature is to keep the logic out of templates, but there are scenarios where logic drives the template.

In the handlebar notation the below does not work as you are trying to do a conditional comparison. This is because helper can only test for properties to be true or false but not arbitrary expressions.

{{#if value == 'Monday'}}
// something
{{/if}}

Now to compare or doing any other operations we are going to register a helper as shown below

Handlebars.registerHelper('ifCondition', function(op1, operator, op2, options) {
  var result = false;
  switch(operator) {
    case '===':
      result = op1 === op2; 
      break;
    case '!==':
      result = op1 !== op2;
      break;
    case '<=':
      result = op1 <= op2;
      break;
    case '>=':
      result = op1 >= op2;
      break;
    case '||':
      result = op1 || op2;
      break;
    case '&&':
      result = op1 && op2;
      break;
  }
  return result ? options.fn(this) : options.inverse(this);
});

Now you have to call it from the Handlebars Template as shown below

{{#ifCond val1 '===' val2}}
  {{result}}
{{ifCond}}


While doing this you might encounter an error like "Error: ifCond doesn't match if - 4:7". This happened because when you convert your if conditional to ifCond you have to change both the opening expression and closing expression. If you do not change the closing expression you will get this error which is saying that your ifCond is not matching with your if.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.


No comments:

Post a Comment