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

标签 symfony twig

我有一个多维数组,其中一些对象存在,而另一些则不存在。我不断收到

对象“stdClass”的方法“code”不存在于...

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

{% for item in items %}
    <p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}

某些产品没有此代码,不幸的是,此数据结构是通过提要提供的,因此我无法更改它。

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

最佳答案

快速查找了一下,希望这对您有用:p

defined

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/

相关文章:

html - 纯 PHP/HTML View VS 模板引擎 View

javascript - 禁用动态创建的 Javascript 的缓存

Symfony2 : Doctrine : PHPUnit : Set entity Id during flushing with mocked entity manager in unit tests

symfony - 自 Symfony 2.8 以来生成 bundle 时询问多应用程序的新选项

php - 在 Symfony2 中使用动态放置的 HTML 渲染 Twig 模板?

php - 如何获取 TWIG 中的当前 URL 或路由?

php - Symfony 中的无效表单,没有错误

php - Symfony 3 连接到多个数据库

html - 在 Twig 生成的表单上使用 tabindex

javascript - 在 Electron js 中模板化数据库查询