pet*_*ete 3 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 %}
Run Code Online (Sandbox Code Playgroud)
您可以使用Array#indexOf:
{% if dtSettings.indexOf('isTime') !== -1 %}checked{% endif %}
{% if dtSettings.indexOf('isTime') === -1 %}hide{% endif %}
Run Code Online (Sandbox Code Playgroud)
或者创建一个自定义过滤器让生活更轻松:
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 %}
Run Code Online (Sandbox Code Playgroud)
AFAIK,该in运算符仅适用于对象。