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">
{{#each students}}
<td>{{ }}</td>
<td>{{ this.mark }}</td>
<td>{{ this.subject }}</td>
<td>{{ }}</td>
<td>{{ this.birthday }}</td>

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}}
            <td>{{getStudentValue }}</td>
            <td>{{getStudentValue this.mark }}</td>
            <td>{{getStudentValue this.subject }}</td>
            <td>{{getStudentValue }}</td>
            <td>{{getStudentValue this.birthday }}</td>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download