user3669481 user3669481 - 1 year ago 55
Javascript Question

Handlebars output null for missing fields

I am trying to use handlebars to format data received from a JSON file. My current structure is something similar to this:

<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Mark</th>
<th>Subject</th>
<th>School</th>
<th>Birthday</th>
</tr>
</thead>
<tbody>
{{#each students}}
<tr>
<td>{{ this.name }}</td>
<td>{{ this.mark }}</td>
<td>{{ this.subject }}</td>
<td>{{ this.school }}</td>
<td>{{ this.birthday }}</td>
</tr>
{{/each}}
</tbody>
</table>


The JSON file I have does not have consistent structure, some student element only contains name (missing all other fields), and some only contain name and school.

If I am using my current code to template the JSON file, I will be getting a table with a lot of blank cells which I would like to write in "null" instead.

I was thinking maybe I should write a registerhelper but if so, how exactly should I do it?

Answer Source

You could define a handlebars helper as follows:

Handlebars.registerHelper("getStudentValue", function(val) {
    if(val === undefined) {
        return "null";
    }
    return val;
});

And the corresponding markup would look like:

 {{#each students}}
        <tr>
            <td>{{getStudentValue this.name }}</td>
            <td>{{getStudentValue this.mark }}</td>
            <td>{{getStudentValue this.subject }}</td>
            <td>{{getStudentValue this.school }}</td>
            <td>{{getStudentValue this.birthday }}</td>
       </tr>
  {{/each}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download