Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor + Blaze - If else statement

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}} 
like image 540
dayuloli Avatar asked Dec 16 '14 10:12

dayuloli


2 Answers

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> 
like image 180
David Weldon Avatar answered Sep 21 '22 23:09

David Weldon


Following on from @David Wheldon's excellent answer, it's also worth noting that you can pass parameters to your JavaScript helper functions from your Blaze template.

So, for example the code below selectively renders the options for a select list by calling the helper method with the line isSelected region customerCompany:

    {{#if isSelected region customerCompany}}         <option value={{region._id}} selected>{{region.name}}</option>     {{else}}         <option value={{region._id}}>{{region.name}}</option>     {{/if}} 

and then in the js file:

isSelected: function (region, customer) {      return customer.salesRegionId === region._id; }, 

This approach of passing in your variables to your helpers is generally recommended to avoid the confusion that can the arise with the changing meaning of the this keyword when using templates.

like image 21
tomRedox Avatar answered Sep 24 '22 23:09

tomRedox