gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:11:56 25 4
gpt4 key购买 nike

我在新项目中使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com