10

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

I have an object we'll call var 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 | length, var | first, and just plain var for the condition, but none of them work, they all just evaluate to true (or false), regardless of whether or not var 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 empty filter for objects which does what I need:

env.addFilter('empty', function(object) {
    return Object.keys(object).length === 0;
});
Mogzol
  • 1,405
  • 1
  • 12
  • 18

1 Answers1

27

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 %}
brew
  • 473
  • 7
  • 6
  • God bless you and your family. But can you give some more information on how should I really "understand" that syntax? Because it makes no sense to me :) – BBerastegui Apr 19 '19 at 18:42
  • 2
    @BBerastegui the `length` filter returns the number of items within an object. If `var` in this case is an empty object, then it returns a length of 0. This evaluates to false therefore the `if` condition does not run. On the other hand any positive `length` would evaluate to true and the condition block would run. – filip Oct 22 '19 at 18:52