Meteor + Blaze - If else statement

dayuloli picture dayuloli · Dec 16, 2014 · Viewed 37.2k times · Source

Looking at this Using Blaze guide, it seems Blaze supports {{#if}} and {{else}} statements, but I have't seen examples of an if-else statement. Is this supported in Blaze? Or do I have to do an additional if block inside the else block, which can get ugly.

I tried {{else if}}, but that gave an error.

{{#if en}}{{text.en}}{{else if tc}}{{text.tc}}{{/if}}

Answer

David Weldon picture David Weldon · Dec 16, 2014

Spacebars uses the same control flow structure as handlebars so the answer is the same as this one. In your case:

{{#if en}}
  {{text.en}}
{{else}}
  {{#if tc}}
    {{text.tc}}
  {{/if}}
{{/if}}

Side note - one of the nice things about jade is that it supports else if.


Sometimes a better alternative is to move the logic into a helper like this:

Template.myTemplate.helpers({
  textValue: function() {
    if (this.en) {
      return this.text.tc;
    } else if (this.tc) {
      return this.text.tc;
    }
  }
});
<template name="myTemplate">
  <p>{{textValue}}</p>
</template>