php - "detailIndex"的 Twig 错误项目 "Array"不存在于

标签 php symfony twig

我正在研究 symfony 并且想在我的 twig 模板中显示一个变量。 这是我的 PHP 代码:

{% for row in issue.data %}
    {{ dump(row) }}

那是我在我的网站上得到的:

array(size=5)
  'positionId' =>int5
  'position' =>int5
  'cost' =>float3000
  'detailIndex' =>int1
  'hours' =>int3

所以我正在使用:

{{ row.detailIndex }}

访问我的数组变量,但出现错误:

Item "detailIndex" for "Array" does not exist in 

这很奇怪,因为我可以很容易地访问这个变量:

{{ row.hours }}
{{ row.position }}
{{ row.cost }}

我会很感激你的 friend 们的帮助!

最佳答案

我认为您应该在访问 detailIndex 键之前检查它是否存在。

解决方案 1 如果 detailIndex 键不存在,则创建它以避免 terners

{% for row in issue.data %}

  {% if row.detailIndex is not defined %}
    {% set row.detailIndex = '' %}
  {% endif %}

... your business here

{% endfor %}

解决方案 2 使用 terner 获取您的 detailIndex 值。这行得通,但读起来不好:)

{{ row.detailIndex is defined ? row.detailIndex : '' }}

解决方案 3 使用 default 过滤器避免未定义属性异常

{{ row.detailIndex | default('') }}

关于php - "detailIndex"的 Twig 错误项目 "Array"不存在于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577355/

相关文章:

symfony - 自定义表单错误 symfony 4

forms - Symfony2 表单集合即使 'by_reference' => false 也不调用 addxxx 和 removexxx

php - Twig embed 与 include,任何使用 include 的理由

php - 表单生成器中的过滤器集合 [symfony2]

php - 我如何配置/应用条件到我的查询以获得结果?

php - 自定义 SEO Yoast 的元标记

php - 如果存在另一个meta_key,则插入meta_key

php - 在特定 DIV 中显示时隐藏 DIV

php - Behat 3 - 如何在上下文中检索自定义扩展

php - 'Twig_Error_Syntax' 消息未知 "form_start"函数