如何检查树枝是否存在值?

How can I check if a value exists with twig?

我在打印前检查了我的值是否存在:

{% if address.company|length %}{{ address.company}}{% endif %}

但我仍然收到一条错误消息:

Key "company" does not exist as the array is empty.

尝试使用 empty twig function:

{% if address.company is not empty %}
    {{ address.company }}
{% endif %}

使用默认过滤器,您可以轻松验证 company 是否存在且同时不为空:

{% if address.company|default %}
    The company is not empty
{% else %}
    The company is empty.
{% endif %}