Search code examples
javascriptif-statementmustache

How do I do an if with value in mustache.js?


I have the following code:

    <script id="tplPLDSemanal" type="text/template">
       {{#.}}
          <tr>  
              <td width="20%">{{Peso}}</td>                                                                                                                             
              <td width="20%">{{SECO}}</td>
              <td width="20%">{{Sul}}</td>
              <td width="20%">{{Nordeste}}</td>
              <td width="20%">{{Norte}}</td>
          </tr>
       {{/.}}
   </script>

and I would like to do something like the following, but it does not work

if ({{Peso}} == 2) 
   <td width="20%">Leve</td>
else if({{Peso}} == 4)
        <td width="20%">Media</td>
     else
        <td width="20%">Pesado</td> 

anyone could help me?


Solution

  • Mustache allows you to use functions inside the template, you can add a function to your data and add the logic you want inside the template.

    Consider the following template:

    <script id="template" type="text/template">
           {{#.}}
              <tr>
                  <td width="20%">{{checkPeso}}</td>
                  <td width="20%">{{SECO}}</td>
                  <td width="20%">{{Sul}}</td>
                  <td width="20%">{{Nordeste}}</td>
                  <td width="20%">{{Norte}}</td>
              </tr>
           {{/.}}
       </script>
    <table id="target"></table>
    

    The first variable is checkPeso which is the name of the function we will add to our data.

    Consider the following data:

    var data = [];
    data.push({'SECO': 'val1a', 'Sul': 'val1b', 'Nordeste': 'val1c', 'Norte': 'val1d', 'peso': 0});
    data.push({'SECO': 'val2a', 'Sul': 'val2b', 'Nordeste': 'val2c', 'Norte': 'val2d', 'peso': 2});
    data.push({'SECO': 'val3a', 'Sul': 'val3b', 'Nordeste': 'val3c', 'Norte': 'val3d', 'peso': 4});
    

    You simply add the function to the data object with the name checkPeso. Inside the function you have access to the data that is being rendered and you can access the data via this.

    data.checkPeso = function () {
        if (this.peso === 2) return 'Leve';
        if (this.peso === 4) return 'Media';
    
        return 'Pesado';
    };
    

    Then, you render as usual your Mustache template:

    var template = $('#template').html();
    Mustache.parse(template); // optional, speeds up future uses
    var rendered = Mustache.render(template, data);
    $('#target').html(rendered);
    

    See full demo here

    Note: As it is correctly stated, Mustache is logic-less but it allows you to use functions and so you can add logic in your template.