3

Is there a way to make a switch statement in Mustache.js

I have a variable which can be one of the four different values. Depends on its value I want to output slightly different template.

Is there a way to do this?

P.S I have seen this question, but nevertheless the question sounds the same, but in the answer the person was answering how to achieve if/else functionality, which I can find here.

Explanation about the code:

I have a list of templates

var templates = {
    friends :
        'here there is some html with {{vars}}'+
        'and a button on which I have to write something like'+
        'add to friends | already your friend | invitation was sent | your invitation was rejected'
    }
}

So basically I am doing an ajax call and together with vars it returns me type, which can be one of the following things 0,1,2,3. Depending on this, I have to write specific text

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753

1 Answers1

5

Edit: I'm assuming you're using javascript. After seeing your use case you can resolve this by passing a function to mustache, for example:

function getType(){
    switch(viewObject.typeid){
    //your cases here return what you want the function to print
    }
}

now, the object you send to mustache should have typeid, this will allow you to move the logic from Mustache (which is again, logicless) back to javascript. Then you can place {{{getType}}} in your code.

Original:

If I may ask, what is the specific usage you need your switch/case statement for? There may be a simpler solution using Mustache. I've written a lot of Mustache code and never ran into a "switch-case" scenario that was not better solved with passing a function with the view-model

Remember that you can pass a function as a parameter to Mustache, this will allow you to move the logic from Mustache back to the view-model which is (most of the times) a good thing.

If that is not the case you can always switch the handlebars:

Mustache is used for logicless templating. If you find out that you have too much logic in your templating, Mustache is probably not the correct choice for you, you can use Handlebars instead which extends Mustache, any current mustache code you have will continue to work.

http://handlebarsjs.com/

Although handlebars does not contain switch-case statements, it allows you to write if/else statements in a much simpler manner, and it will allow you to define helper functions which can accomplish your functionality.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504