Hugo数据无法传入循环迭代问题排查求助
问题:无法访问Hugo数据文件tabs.yaml中的内容生成导航项
我在Hugo项目中尝试通过partial迭代生成导航<li>元素,但始终无法读取data/tabs.yaml里的数据,试过$var赋值写法也没解决问题。
现有代码
1. layouts/partials/homepage/section_2.html
<div class="container-fluid"> <div class="row"> <ul class="nav nav-tabs" id="myTab" role="tablist"> {{ range .topics.navitems }} <li class="nav-item" role="presentation"> {{ with .title }} <button class="nav-link" id="{{ .id }}-tab" data-bs-toggle="tab" data-bs-target="#{{ .id }}-tab-pane" type="button" role="tab" aria-controls="{{ .id }}-tab-pane" aria-selected="false">{{ . }}</button> {{ end }} </li> {{ end }} </ul> </div> </div>
2. layouts/index.html 代码片段
{{define "main"}} {{partial "homepage/section_1.html"}} {{ with .Site.Data.home.topics}} {{partial "homepage/section_2.html"}} {{end}} {{partial "homepage/section_3.html"}} {{partial "homepage/section_4.html"}} {{partial "homepage/section_5.html"}} {{end}}
3. data/tabs.yaml 内容
enabled : true id : "topics" content : title : "Browse Topics" navitems : - id : "marketing" title : "Our Services" url : "/services" - id : "design" title : "Why Us?" url : "/whyus" - id : "finance" title : "About Us" url : "/aboutus" - id : "music" title : "Properties" url : "/properties" - id : "education" title : "Education" url : "/education"
问题排查与修复方案
1. 修正数据文件路径引用
你的index.html中调用的是.Site.Data.home.topics,但数据文件实际是data/tabs.yaml,正确的路径应为.Site.Data.tabs。
2. 给Partial传递上下文数据
调用partial时必须明确传递数据上下文,否则partial无法获取目标数据。修改index.html中的partial调用:
{{ with .Site.Data.tabs}} {{partial "homepage/section_2.html" .}} {{end}}
这里的.表示将当前with块中的tabs.yaml根数据传递给partial。
3. 修正Partial内部的变量引用
section_2.html中存在两处错误:
- 原代码用
range .topics.navitems,但传递的上下文是tabs.yaml根数据,navitems实际在content字段下,应改为range .content.navitems {{ with .title }}块会把上下文切换为标题字符串,导致无法访问.id,直接移除该with块,用.title直接获取导航项标题
修改后的section_2.html:
<div class="container-fluid"> <div class="row"> <ul class="nav nav-tabs" id="myTab" role="tablist"> {{ range .content.navitems }} <li class="nav-item" role="presentation"> <button class="nav-link" id="{{ .id }}-tab" data-bs-toggle="tab" data-bs-target="#{{ .id }}-tab-pane" type="button" role="tab" aria-controls="{{ .id }}-tab-pane" aria-selected="false">{{ .title }}</button> </li> {{ end }} </ul> </div> </div>
4. 调试验证(可选)
如果仍有问题,可在index.html中添加以下代码,确认数据是否正确加载:
<pre>{{ jsonify .Site.Data.tabs }}</pre>
内容的提问来源于stack exchange,提问作者Joel Wong
相关产品推荐
相关产品推荐

