如何检查Symfony2中Twig模板引擎中是否存在对象?

Ada*_*cey 83 symfony twig

我有一个多维数组,其中存在一些对象而其他对象则不存在.我一直在接受

对象"stdClass"的方法"代码"在...中不存在

我在模板中使用的代码是:

{% for item in items %}
    <p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

有些产品没有这个代码,不幸的是这个数据结构是通过feed提供的,所以我无法改变它.

当我查看Twig文档时,我解释说如果没有对象或方法,它只会返回null?

Tjo*_*rie 148

快速查找,希望这对你有用:p

定义

如果在当前上下文中定义了变量,则定义检查.如果您使用strict_variables选项,这非常有用:

{# defined works with variable names #}
{% if foo is defined %}
    ...
{% endif %}

{# and attributes on variables names #}
{% if foo.bar is defined %}
    ...
{% endif %}
Run Code Online (Sandbox Code Playgroud)