Search code examples
nunjucks

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

  • 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>