JSON Object into Mustache.js Table

谁说胖子不能爱 提交于 2019-11-30 05:21:42

问题


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":"john@gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary@gmail.com"}]'
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>

回答1:


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.




回答2:


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":"john@gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary@gmail.com"}]'
var obj = {people: JSON.parse(text)};

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


来源:https://stackoverflow.com/questions/24923871/json-object-into-mustache-js-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!