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

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}} &middot; {{.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}} &middot; {{.Date.Format "January 2, 2006"}}</a></h3>
                    {{ end }}
                </div>
            </section>
        </li>
        {{end}}
    {{end}}
</ul>
{{ end }}

内容的提问来源于stack exchange,提问作者Aditya Mayukh Som

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:17:26