简体   繁体   中英

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 %}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM