我有一个多维数组,其中一些对象存在,而另一些则不存在。我不断收到
对象“stdClass”的方法“code”不存在于...?
我在模板中使用的代码是:
{% for item in items %}
<p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}
某些产品没有此代码,不幸的是,此数据结构是通过提要提供的,因此我无法更改它。
当我查看 Twig 文档时,我解释说如果对象或方法不存在,它只会返回 null?
最佳答案
快速查找了一下,希望这对您有用:p
define 检查变量是否在当前上下文中定义。如果您使用 strict_variables 选项,这将非常有用:
{# defined works with variable names #}
{% if foo is defined %}
...
{% endif %}
{# and attributes on variables names #}
{% if foo.bar is defined %}
...
{% endif %}
关于symfony - 如何检查 Symfony2 的 Twig 模板引擎中是否存在对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034060/