如何检查数组元素是否在树枝文件中定义


How to check whether array element is defined or not in twig file?

我正在尝试访问数组,但它没有被访问。在我的 config.yml 中,以下是我的数组:

abc : [xyz]

在另一个文件中,我正在编写以下代码来访问 abc 数组。

 {% if abc[0] is defined) %}
then do something
  {% endif %}

但不知何故它不起作用。 请帮助我,我是新手。

这取决于变量是否总是被声明:

如果始终声明变量并且数组可以为空

{% if abc is not empty %}
    {# then do something #}
{% endif %}

Twig 中的<variable> is not empty相当于 PHP 中的!empty($variable)。当提供数组时,is not empty将检查数组中是否有值和/或值。

empty Twig 文档中的测试。

如果变量并不总是声明

检查 abc 变量是否已声明且不为空:

{% if (abc is declared) and (abc is not empty) %}
    {# then do something #}
{% endif %}

Twig 中的<variable> is declared相当于 PHP 中的isset($variable)

defined Twig 文档中的测试。

根据注释,我建议改用 foreach 循环,并根据索引值定义 ifs。像这样:

{% for abcs in abc %}
    {% if (loop.index == 0) %}
         then do something
    {% endif %}
{% endfor %}

BR的