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