JSON Object into Mustache.js Table

10,283

Solution 1

In additon to your own solution, you should consider using mustache to repeat the row for you:

<script id="user-template" type="text/template">
{{#people}}
<tr>
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>

 

var text = '[{"Fullname":"John", "WorkEmail":"[email protected]"},{"Fullname":"Mary", "WorkEmail":"[email protected]"}]'
var obj = {people: JSON.parse(text)};

$(document).ready(function() {
    var template = $('#user-template').html();
    var info = Mustache.render(template, obj);
    $('#ModuleUserTable').html(info);
});

Solution 2

I figured out that instead of

$('#ModuleUserTable').html(info);

it should be :

$('#ModuleUserTable').append(info);

Template should be :

<script id="user-template" type="text/template">
<tr>
    <td>{{FullName}}</td>
    <td>{{WorkEmail}}</td>
</tr>
</script>

and ID should not be on the table row tag. Instead it should be on the table itself:

<table border="1"  id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>

The moment when it appends, it adds a new row into the table with the JSON data.

Share:
10,283
Joshua Tan
Author by

Joshua Tan

New to programming, Learning in progress...

Updated on June 10, 2022

Comments

  • Joshua Tan
    Joshua Tan about 2 years

    I'm trying to create a table with a JSON Object using Mustache.js. I wanted it to show two rows, however it's only showing the second row only. I suspect that the first row is being overwritten by the second when it's being bound again in the loop.

    How do I work my way around it? Or is there a better structure I should follow?

    Javascript:

    var text = '[{"Fullname":"John", "WorkEmail":"[email protected]"},{"Fullname":"Mary", "WorkEmail":"[email protected]"}]'
    var obj = JSON.parse(text);
    
    $(document).ready(function() {
            var template = $('#user-template').html();
            for(var i in obj)
            {
            var info = Mustache.render(template, obj[i]);
            $('#ModuleUserTable').html(info);
            }
    }); 
    

    Template :

    <script id="user-template" type="text/template">
        <td>{{FullName}}</td>
        <td>{{WorkEmail}}</td>
    </script>
    

    table:

    <table border="1">
    <tr>
    <th>FullName</th>
    <th>WorkEmail</th>
    </tr>
    <tr id = "ModuleUserTable"> 
    </tr> 
    </table>