Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Object into Mustache.js Table

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>
like image 962
Joshua Tan Avatar asked Jul 24 '14 01:07

Joshua Tan


2 Answers

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);
});
like image 187
RoToRa Avatar answered Oct 10 '22 23:10

RoToRa


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.

like image 26
Joshua Tan Avatar answered Oct 10 '22 23:10

Joshua Tan