Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I accomplish an if/else using comparison in mustache.js?

I read how to use if/else in mustache.js in this article.

Now my question, it is possible to use in if statement the comparison operators ?

like (just I gave a wrong example):

{{#ItemIndex==0}}
   <td>{{ItemIndex}}</td>
{{/ItemIndex}}
{{^ItemIndex==0}}
   <td>{{ItemIndex}} *</td>
{{/ItemIndex}}

How to do that ?

like image 955
Snake Eyes Avatar asked Oct 22 '22 01:10

Snake Eyes


1 Answers

You can't do that using Mustache.

However, since you're interested in the value that equals 0 (falsy), you can do this:

/*
Template:
{{#objs}}
    {{^ItemIndex}}
        {{ItemIndex}}*
    {{/ItemIndex}}
    {{#ItemIndex}}
        {{ItemIndex}}
    {{/ItemIndex}}
{{/objs}}"
*/

var template = "{{#objs}}{{^ItemIndex}}{{ItemIndex}}*{{/ItemIndex}}{{#ItemIndex}}{{ItemIndex}}{{/ItemIndex}}\n\n{{/objs}}"

document.getElementsByTagName('body')[0].textContent = (Mustache.render(template, {objs: [
    {
        ItemIndex: 0
    }, 
    {
        ItemIndex: 1
    },    
    {
        ItemIndex: 2
    } 
]}))

// result => 0* 1 2

Fiddle

If you need if/else constructs in your templates and like the Mustache syntax, you should check out Handlebars.js.

like image 50
pdoherty926 Avatar answered Nov 09 '22 08:11

pdoherty926