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

Hugo基础模板嵌套失败求助:如何实现多层模板继承?

解决Hugo模板嵌套继承的空白问题

错误原因

layouts/posts/baseof.html仅用define "body"定义了块,但没有作为完整模板去继承根目录的baseof.html,Hugo无法识别这个模板的入口,最终输出空白。

正确配置

  1. 保持根baseof不变:layouts/_default/baseof.html无需修改,它是所有页面的基础框架:
<html>
    <body>
        <span>main baseof.html</span>
        {{ block "body" . }} 
        
        {{ end }}
    </body>
</html>
  1. 修改posts的baseof模板:让它继承根baseof并填充body块,同时定义main块供single.html使用:
{{/* 继承根目录的基础模板 */}}
{{ template "_default/baseof.html" . }}

{{/* 重写根模板中的body块 */}}
{{ define "body" }}
    <span>posts baseof.html</span>
    {{ block "main" . }}
    {{ end }}
{{ end }}
  1. 保持posts/single.html不变:它定义的main块会自动填充到posts baseof的对应位置:
{{ define "main" }}
    <h1>{{ .Title }}</h1>
            
    {{ .Content }}
{{ end }}

效果验证

这样配置后,渲染posts页面时会按层级嵌套:根baseof的html结构 → posts baseof的body内容 → single.html的main内容,最终输出和你期望的完全一致。

内容的提问来源于stack exchange,提问作者Nishant George Agrwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:36:26