简体   繁体   English

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

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

I'm using Swig on a new project. 我在一个新项目上使用Swig。 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? Swig中是否有内置运算符来检查数组中是否存在值? 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 : 您可以使用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. AFAIK, in运算符仅适用于对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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