javascript - Swig 模板 : How to check if value exists in array?

标签 javascript arrays swig-template

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

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

最佳答案

你可以使用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 %}

据我所知,in 运算符仅适用于对象。

关于javascript - Swig 模板 : How to check if value exists in array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31812149/

相关文章:

javascript - 在 Firefox 中重复单击按钮

javascript - Swig 模板,测试条件

c++ - <Swig 类型为 'std::map< char,int > 的对象的代理

javascript - HTML/JS 实时测试网站

javascript - 如何递归处理 JSON 数据并从函数返回处理后的 JSON?

javascript - 从移动浏览器上的 Web 应用程序自动调用电话号码

javascript - 将具有相同键值的数组中的 JavaScript 对象组合在一起

JAVA:如何将字符串ArrayList转换为整数ArrayList?

javascript - 如何在 JavaScript 中查找对象数组中的重复项?

javascript - 当尝试在 koajs 上使用 swig 渲染模板时,浏览器中的 "not found"纯文本