Reputation: 4413
In Handlebars I am looping through a list and am building a table based on the values as follows:
<table class="table table-striped table-condensed">
<thead>
<tr>
{{#each header}}
<th data-id="{{@index}}" style="cursor: pointer">{{this.label}} <i class=" icon-resize-vertical"></i></th>
{{/each}}
</tr>
</thead>
<tbody>
{{#each objects}}
<tr>
{{#each this.properties}}
<td>
{{#if @first}}
<a data-id="{{subIndex ../../this}}">{{this}}</a>
{{/if}}
{{#unless @first}}
{{#if this}}
{{this}}
{{/if}}
{{/unless}}
</td>
{{/each}}
</tr>
{{/each}}
</tbody>
</table>
The part that is giving me problems is the section:
{{#unless @first}}
{{#if this}}
{{this}}
{{/if}}
{{/unless}}
The purpose of this section is to check first if the current value in the loop is not null, and if it is not null, then display it. Otherwise, just skip it. However, this outputs
[object Window]
as if the value of this
is somehow not bound to the current place in the loop.
My question is basically, do I need to be checking for a null value some other way?
Upvotes: 1
Views: 8244
Reputation: 31
I used a helper as a filter function. Something like this:
Handlebars.registerHelper({
'notNull': function(value, options) {
if(!Handlebars.Utils.isArray(value)){
return [];
} else {
return value.filter(function(ele){
return !Handlebars.Utils.isEmpty(ele);
});
}
}
Handlebars code:
{{#each (notNull elements)}}
{{this}}
{{/each}}
With the context:
{elements:[{...},{...},{...},{...}]}
I had to use this solution because sometimes the read array could contain null elements. In this case the original array was reduced to non-empty elements.
For example running this in Handlebars 4.0.12:
{
"elements": [{
"unid": "1AB9BD4361CC9C2FC125832E00378BBF"
}, {
"unid": "4B8D99F9775B2E93C1258329002E8297"
}, {
"unid": "BFFA0EB7B3384AF7C1258328003758D0"
}, {
"unid": "7EDFA3EA1B588028C125832700378438"
},
null
]
}
{{#each (notNull elements)}}
{{this.unid}}
{{/each}}
produces:
1AB9BD4361CC9C2FC125832E00378BBF
4B8D99F9775B2E93C1258329002E8297
BFFA0EB7B3384AF7C1258328003758D0
7EDFA3EA1B588028C125832700378438
Upvotes: 1
Reputation: 374
Did you find a solution for this? I was having the same issue, solution was to create a handlebars helper. First time I tried this I just added a conditional to check for null. Turns out the value of this is set to an instance of window at compile so just changed the conditional to check for instance of Window.
Handlebars.registerHelper('notNull', function(value, options) {
if((value instanceof Window) == false) {
return options.fn(this);
}
return options.inverse(this);
});
This works with the following handlebars code
{{#notNull this}}
{{this}}
{{/notNull}}
Upvotes: 3