我正在研究 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/