user3087483 user3087483 - 6 months ago 19
HTML Question

feed json data into html table

I need to build a table based on json response i'm getting when calling API,
calling the API and get the JSON works fine, just I didn't found any documentation about building a table and pass from x.js to x.html. I succeed to pass only 1 param/value from the json.

my json looks like this: (it's Jenkins API result)

{
"builds":
[
{
"duration": 24503,
"id": "2013-12-11_19-48-55",
"number": 33,
"result": "FAILURE",
"timestamp": 1386791335164
},
{
"duration": 24553,
"id": "2013-12-11_19-00-27",
"number": 32,
"result": "FAILURE",
"timestamp": 1386788427803
},
{
"duration": 24237,
"id": "2013-12-11_18-59-51",
"number": 31,
"result": "FAILURE",
"timestamp": 1386788391179
},


JS Code

Meteor.call('jenkinsServiceBuild', function(err, respJson) {

if(err) {
window.alert("Error: " + err.reason);
console.log("error occured on receiving data on server. ", err );
} else {
//window.alert("Success: ");
console.log("respJson: ", respJson.builds[1].id);
//window.alert(respJson.length + ' tweets received.');
var buildsList = respJson.builds[1].id;
Session.set("recentBuilds", respJson.builds[1].id);
}
$('#buildButton').removeAttr('disabled').val('build');
})
},
});

Template.dashboard.helpers({
recentBuilds : function() {
return Session.get("recentBuilds");
//recentBuilds: buildsList


}
});

HTML Code

<template name="dashboard">
<div class="control-group">
<div class="controls">
<input type="button" value="build" class="btn btn-info" id="buildButton"/>
</div>
<br><br>
___{{recentBuilds}}___

</template>


Thanks
Ronen

Answer

You could do something like this in your html instead of ___{{recentBuilds}}___

<table>
    <thead>
        <th>Duration</th><th>ID</th><th>Number</th><th>Result</th><th>Timestamp</th>
    </thead>
    <tbody>
    {{#each recentBuilds}}
        <tr>
            <td>{{duration}}</td>
            <td>{{number}}</td>
            <td>{{result}}</td>
            <td>{{timestamp</td>
        </tr>
    {{else}}
        <tr>
            <td colspan="4">No data</td>
        </tr>
    {{/each}}
</table>

Also in your callback return all the data instead of one value so it can be iterated through:

instead of

Session.set("recentBuilds", respJson.builds[1].id);

Return everything in builds.

Session.set("recentBuilds", respJson.builds);

So now because everything in builds is an array, when you use {{#each}} it would loop through these in your html and create a row for each one.