'Nunjucks check for object or string

How can I check if a variable is an object or string in an if block? It seems one can not call functions inside the {% if ... %} block. And the other {{ if() }} syntax seems only to be for inline conditions.

I solve it now to test for some object properties that should be there when the variable is an object, but there should be a better solution. Like an isObject or isString function



Solution 1:[1]

You could use a custom filter:

var env = new nunjucks.Environment();

env.addFilter('is_string', function(obj) {
  return typeof obj == 'string';
});

This is what the template would look like:

{% if item|is_string %}yes{% endif %}

var env = new nunjucks.Environment();

env.addFilter('is_string', function(obj) {
  return typeof obj == 'string';
});

var res = env.renderString("{% if item|is_string %}yes{% endif %}", { item: 'test' });

document.body.innerHTML = res;
<script src="https://mozilla.github.io/nunjucks/files/nunjucks.js"></script>

Solution 2:[2]

Custom filter or maybe you can...

if (string(foo) == foo) { // string }
else { // object }

Solution 3:[3]

You could use the built-in test of a string:

{% if foo is string %}
   It is a string
{% endif %}

The is-keyword marks the condition as a nunjucks/jinja-test. The word string refers to the built-in test.

See for tests the jinja-description:

Nunjucks is inspired by jinja2. I have not found a nunjucks-documentation about tests, but the string test works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ja͢ck
Solution 2 Félix Sanz
Solution 3 codica