javascriptarraysswig-template

Swig Templates: How to check if value exists in array?


I'm using Swig on a new project. One of my variables is an array of values (strings). Is there a built-in operator in Swig to check if a value exists in an array? Per the docs, it would seem "in" should do it but no further detail is provided. Also, what's the proper way to negate it? I'm trying the following, but no luck. Would I need to write a custom tag?

{% if 'isTime' in dtSettings %}checked{% endif %}

{% if 'isTime' not in dtSettings %}hide{% endif %}
{% if !'isTime' in dtSettings %}hide{% endif %}
{% if !('isTime' in dtSettings) %}hide{% endif %}

Solution

  • You can use Array#indexOf:

    {% if dtSettings.indexOf('isTime') !== -1 %}checked{% endif %}
    {% if dtSettings.indexOf('isTime') === -1 %}hide{% endif %}
    

    Or create a custom filter to make life a bit easier:

    swig.setFilter('contains', function(arr, value) {
      return arr.indexOf(value) !== -1;
    });
    
    // In your template:
    {% if dtSettings|contains('isTime') %}checked{% endif %}
    {% if not dtSettings|contains('isTime') %}hide{% endif %}
    

    AFAIK, the in operator applies to objects only.