You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twig提示无法在整数变量上访问属性,如何跳过null/整数场景报错?

解决方法

方案1:Twig端直接修复(无需修改后端代码)

  • 如果你的Twig版本≥2.12,直接使用空安全运算符?.访问属性,当decoded不是可访问属性的对象/数组时,会直接返回null不报错:
    {{ item.decoded?.startDate }}
    
  • 低版本Twig可以使用default过滤器兜底,或提前判断属性是否存在:
    {# 方式1:用default过滤器设置默认值 #}
    {{ item.decoded.startDate|default('') }}
    
    {# 方式2:条件判断后输出 #}
    {% if item.decoded is object and item.decoded.startDate is defined %}
      {{ item.decoded.startDate }}
    {% endif %}
    

方案2:后端控制器端修复(从源头统一数据格式)

在控制器处理decoded字段时,保证该字段永远为对象类型,避免后续Twig层面频繁判断:

foreach ($data as $d) {
    $decoded = json_decode($d->getValue());
    // 仅当json_decode返回对象时保留结果,否则赋值为空对象
    $d->decoded = is_object($decoded) ? $decoded : new \stdClass();
}

如果需要给缺失的startDate设置统一默认值,可以进一步调整:

foreach ($data as $d) {
    $decoded = json_decode($d->getValue());
    if (!is_object($decoded)) {
        $decoded = new \stdClass();
    }
    // 给不存在的startDate设置默认值,可根据业务需求修改
    $decoded->startDate = $decoded->startDate ?? '';
    $d->decoded = $decoded;
}

内容的提问来源于stack exchange,提问作者cervico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:36:03