Reputation: 807
I have a template data context like this:
data = {
"attribute1": {
"attribute2": {}
}
}
And in the meteor template I am doing something like this:
{{#with attribute1}}
{{#if attribute2}}
show some content
{{/if}}
{{/with}}
I don't want to show anything if attribute2 is an empty object. However I tried both {{#with attribute2}}{{/with}}
and {{#if attribute2}}{{/if}}
And it's still rendering the content inside even if it's an empty object.
What is the correct way to check if the object is empty in spacebar template? Or is it even possible?
Upvotes: 2
Views: 3223
Reputation: 1495
The reason why your original code does not work is because you are assuming that an empty object equates to false in Spacebars. As mentioned here in the Spacebars documentation, only falsy Javascript values (null
, undefined
, 0
, ""
, and false
) will be considered false by Spacebars. Therefore, an empty object needs to be checked using a Meteor helper method like your accepted answer suggests.
Upvotes: 0
Reputation: 5075
if attribute2
is an object, you can use Object.keys
to check the length
{{#with attribute1}}
{{#if !!Object.keys(attribute2).length}}
show some content
{{/if}}
{{/with}}
Upvotes: 1
Reputation: 807
I just found a way to register a template helper and use jQuery.isEmpty to do the null check:
Template.registerHelper("isEmpty", function (object) {
return jQuery.isEmpty(object);
});
And to use it in the template:
{{#unless isEmpty attribute2}}
show some content
{{/unless}}
But I found a drawback from this solution that if I want to refer to attributes inside attribute2, I will need to add {{#with attribute2}}{{/with}}
inside the unless block
Upvotes: 2