Hugo首页多区块条件渲染问题:slice用法报错排查
解决Hugo首页模板渲染报错:can’t evaluate field Pages in type string
报错原因
在range $sectionName := $sectionNames循环内部,当前上下文.指向的是循环中的字符串元素(如"posts"),而非Hugo的页面/站点上下文。字符串类型不存在Pages字段,因此调用.Pages会触发该报错。
修复方案
提前将站点全局页面集合保存到变量中,在循环内部使用该变量进行筛选,避免上下文丢失。以下是修正后的模板代码:
{{ define "main" }} <ul class="homepage-topic-sections-container"> <!-- 保存站点全局页面集合到变量,避免循环中上下文丢失 --> {{$sitePages := .Site.Pages}} {{$sectionNames := slice "posts" "problems" "tutorials"}} {{range $sectionName := $sectionNames}} <!-- 筛选出当前section的首页(即section本身) --> {{$section := where $sitePages "Section" . | first}} {{with $section}} <li> <section class="homepage-topic-section"> <h1 class="topic-heading"><a href="{{.Permalink}}">{{.Title}}</a></h1> <div> <!-- 遍历当前section下的所有页面 --> {{ range .Pages }} <h3><a href="{{.Permalink}}">{{.Title}} · {{.Date.Format "January 2, 2006"}}</a></h3> {{ end }} </div> </section> </li> {{end}} {{end}} </ul> {{ end }}
补充优化(替代union的简洁写法)
如果需要一次性合并所有目标section的页面并展示,可使用apply和union结合的方式,避免重复调用union:
{{ define "main" }} <ul class="homepage-topic-sections-container"> {{$sectionNames := slice "posts" "problems" "tutorials"}} <!-- 生成每个section的页面集合,再合并为一个集合 --> {{$allTargetPages := apply $sectionNames "where" .Site.Pages "Section" "." | union}} <!-- 按section分组展示(保持原分组结构) --> {{range $sectionName := $sectionNames}} {{$section := where .Site.Pages "Section" . | first}} {{with $section}} <li> <section class="homepage-topic-section"> <h1 class="topic-heading"><a href="{{.Permalink}}">{{.Title}}</a></h1> <div> {{ range where $allTargetPages "Section" $sectionName }} <h3><a href="{{.Permalink}}">{{.Title}} · {{.Date.Format "January 2, 2006"}}</a></h3> {{ end }} </div> </section> </li> {{end}} {{end}} </ul> {{ end }}
内容的提问来源于stack exchange,提问作者Aditya Mayukh Som
相关产品推荐
相关产品推荐

