Search code examples
jquerymustache

How to loop through an Json array in mustache template


I have an array with JSON object:

{result" : "OK","data":[
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"},
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"}, 
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"}
                   ]
 }

I'm trying to loop through the array to get the 3 fields displayed in my table. However nothing is getting diplayed. Here is my mustache template:

<table style="width:100%;">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>User ID</th>

                            </tr>
                        </thead>
                        <tbody>
                            {{#data}}
                                <tr>

                                    <td>{{name}}</td>
                                    <td>{{id}}</td>

                                </tr>
                              {{/data}}

                        </tbody>
</table>

I'm not able to display any fields in the table.Stuck badly with this..:( :(Any ideas how i can achieve this??


Solution

  • Just went through mustache.I hope this is what you expected.

      $(document).ready(function() {
        var jsonData = {
          "result": "OK",
          "data": [{
            "name": "henrytest",
            "id": "9a3d1faaaac742889a940a6d9df49d16"
          }, {
            "name": "henrytest",
            "id": "9a3d1faaaac742889a940a6d9df49d16"
          }, {
            "name": "henrytest",
            "id": "9a3d1faaaac742889a940a6d9df49d16"
          }]
        }
    
        var Usertemplate = $("#user-template").html();
        $("#userinfo").html(Mustache.to_html(Usertemplate, jsonData));
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script>
    <table style="width:100%;">
      <thead>
        <tr>
          <th>Name</th>
          <th>User ID</th>
        </tr>
      </thead>
      <tbody id="userinfo">
        <script id="user-template" type="text-template">
          {{#data}}
          <tr>
            <td>{{name}}</td>
            <td>{{id}}</td>
    
          </tr>
          {{/data}}
        </script>
      </tbody>
    </table>