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

Grav模块开发问题:Yaml数据在Twig中无法渲染value字段

解决Grav模块中Twig无法读取YAML嵌套content值的问题

我一眼就看出问题出在哪了——你的YAML结构和Twig遍历的路径完全不匹配!

先拆解下你的YAML配置,关键是要注意结构层级:

table:
  - title: Test
    content:
      - value: 'test1'
      - value: 'test2'
      - value: 'test3'

这里的table是一个数组(最开头的-就是数组元素的标识),数组里的第一个元素才是包含title和content的对象。

你之前写的错误Twig代码:

{% for item in page.header.table.content %}
  <h1>{{item.value}}</h1>
{% endfor %}

直接访问page.header.table.content是错的,因为table本身是数组,你得先拿到数组里的那个对象,才能访问它的content属性。

而你能正常读取title的代码:

{% for item in page.header.table %}
  <h1>{{item.title}}</h1>
{% endfor %}

之所以能生效,是因为这个循环遍历的是table数组,每次循环的item就是数组里的那个对象,自然能拿到item.title。

正确的解决方案

根据你的实际使用场景,有两种处理方式:

方式1:如果table数组只会有一个元素(像现在的情况)

直接通过数组索引定位到目标对象,再遍历它的content:

{% for item in page.header.table[0].content %}
  <h1>{{item.value}}</h1>
{% endfor %}

方式2:如果table数组可能有多个元素,需要批量处理

可以用嵌套循环,先遍历table数组,再逐个处理每个数组元素里的content:

{% for table_item in page.header.table %}
  <h2>{{ table_item.title }}</h2>
  {% for content_item in table_item.content %}
    <h1>{{ content_item.value }}</h1>
  {% endfor %}
{% endfor %}

这样就能正确读取到content里的每个value值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:58:37