person66 person66 - 1 year ago 262
Node.js Question

Check if an object is empty in Nunjucks

So I'm using Nunjucks as the templating engine in my Node.js application.

I have an object we'll call

which may or may not be empty.

When it is empty, if I do
{{ var | dump }}
Nunjucks properly shows that it is an empty object, displaying

The problem is, I can't find any way to check if the object is empty using Nunjuck's
{% if condition %}
statement. I have tried
var | length
var | first
, and just plain
for the condition, but none of them work, they all just evaluate to true (or false), regardless of whether or not
is empty. Does anyone know how to solve this?

EDIT: using
{% if var | dump != '{}' %}
does work, but seems like a really hacky solution...

EDIT 2: I ended up just creating a custom
filter for objects which does what I need:

env.addFilter('empty', function(object) {
return Object.keys(object).length === 0;

Answer Source

Support for accessing an object's length with the length filter was recently added in Nunjucks 2.5.0.

So you can now use:

{% if var|length %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download