Twig 如果元素不存在,则出现细枝错误

Twig 如果元素不存在,则出现细枝错误,twig,silex,Twig,Silex,我把Silex和细枝一起用,我想找出一个键的位置 由于密钥并不总是存在,方法1将失败并出现异常。另一方面,方法2没有错误,但是我想避免额外的for和if条件 这能做到吗 方法1: {% if app.session.get('shop').modules.promotion %} exists {% endif %} {% if app.session.get('shop').modules is not empty %} {% for id, config in app.se

我把Silex和细枝一起用,我想找出一个键的位置

由于密钥并不总是存在,方法1将失败并出现异常。另一方面,方法2没有错误,但是我想避免额外的for和if条件

这能做到吗

方法1:

{% if app.session.get('shop').modules.promotion %}
    exists
{% endif %}
{% if app.session.get('shop').modules is not empty %}
    {% for id, config in app.session.get('shop').modules %}
        {% if id == 'promotion' %}
            exists
        {% endif %}
    {% endfor %}
{% endif %}
方法2:

{% if app.session.get('shop').modules.promotion %}
    exists
{% endif %}
{% if app.session.get('shop').modules is not empty %}
    {% for id, config in app.session.get('shop').modules %}
        {% if id == 'promotion' %}
            exists
        {% endif %}
    {% endfor %}
{% endif %}

谢谢

您可以使用已定义的

{% if app.session.get('shop').modules.promotion is defined %}
    exists
{% endif %}
有关定义的
的更多信息,请参见此处: