Swig patterns: how to check if a value exists in an array?
I am using Swig in 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? In the documents, it would seem, "in" should do this, but no further details are provided. Also, what's the correct way to deny it? I am trying to do the following but no luck. Do I need to write my own 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 %}
+3
source to share
1 answer
You can use Array#indexOf
:
{% if dtSettings.indexOf('isTime') !== -1 %}checked{% endif %}
{% if dtSettings.indexOf('isTime') === -1 %}hide{% endif %}
Or create your own filter to make life 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 operator in
only applies to objects.
+4
source to share