Swig模板:如何检查数组中是否存在值?

时间:2015-08-04 14:33:21

标签: javascript arrays swig-template

我在一个新项目上使用Swig。我的一个变量是一个值数组(字符串)。 Swig中是否有内置运算符来检查数组中是否存在值?根据文档,它似乎"在"应该这样做,但没有提供进一步的细节。还有什么,否定它的正确方法是什么?我尝试了以下,但没有运气。我需要写一个自定义标签吗?

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

1 个答案:

答案 0 :(得分:4)

您可以使用Array#indexOf

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

或创建自定义过滤器,让生活更轻松:

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,in运算符仅适用于对象。