Tuesday, December 6, 2016

JavaScript - jQuery templates - Q&A

Question:

Build a jQuery template to show the following JSON in HTML table (“al” stands for a table row):
 
var data {"al":[

    {"id":"0","a":[{"txt":"Person","id":0},

    {"txt":"Description","id":0}]},

    {"id":"1","a":[{"txt":"Maxi","id":1},

        {"txt":"a rock star","id":2}]},

    {"id":"2","a":[{"txt":"Rocky","id":3},

        {"txt":"a rock star's friend","id":4}]},

    {"id":"3","a":[{"txt":"Linda Chavez","id":5},

        {"txt":"a reporter","id":6}]},

    {"id":"4","a":[{"txt":"Bill Winter","id":7},

        {"txt":"an announcer on a radio show","id":8}]}]};
 

Answer


<script id="dataTemplate" type="text/x-jquery-tmpl">
<table>
<tr>
 <th>id</th>
 <th>txt</th>
 <th>id</th>
 <th>txt</th>
</tr>
{{each al}}
 <tr>
{{each a}}
    <td>
    ${id}
    </td>
    <td>
    ${txt}
    </td>
  {{/each}}
 <tr>
{{/each}}
</table>
</script>

No comments:

Post a Comment