mustache.js – table, looping, conditional if-else

mustache.js-conditional-loop-tableconditional.html

<!doctype html>
<html lang="en">
  <head>
    <title>Mustache.js Looping - if else conditional - table </title>
    <script type="text/javascript" src="jquery.min.js" ></script>
    <script type="text/javascript" src="mustache.js" ></script>
    <script>
    $(document).ready(function(){
        
     var data ={
      "headers":["First Name", "Last Name", "year"],
      "employe": [
       {
         "firstName": "John",
         "lastName": "Doe",
         "year": "1985"
       },
       {
         "firstName": "Anna",
         "lastName": "Smith"
       },
       {
         "firstName": "Peter",
         "lastName": "Jones",
         "year": "1995"
       }
      ]
     };
        
   $("#templates").load("template.html #condloop",function(){
     var html = Mustache.render($('#condloop').html(), data);            
     console.log('html',html);
     $('#div1').html(html);      
   });
});
    </script>
  </head>
  <body>
      <style> table { border-collapse: collapse; } table, th, td { border: 1px solid black; } </style>
    <div id="div1"></div>
    
<div id="templates" style="display:none;">
    
</div>
  </body>
</html>

template.html

<div id="conditional">
    {{! for table, you must put code to script tag}}
    <script id='condloop'  type="text/html">
        <table>
        <tr>
<!-- looping data headers-->
        {{#headers}} <th>{{.}}</th> {{/headers}}
<!-- end looping data headers-->
        </tr>
<!-- looping employe-->
        {{#employe}}
            <tr>
                <td>{{firstName}}</td>
                <td>{{lastName}}</td>
                <td>
<!-- condition employe.year -->
{{#year}} <!-- condition if -->
   {{.}}
{{/year}}
{{^year}} <!-- condition else -->
   Not Available
{{/year}}
<!-- condition employe.year -->
                </td>    
            </tr>

        {{/employe}}
<!-- end looping employe-->
        </table>
    </script>
</div>

Published by

G3n1k

just to remember what i had known :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s