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

如何在Go HTML模板中使用带参布局渲染含页眉页脚的首页

Go html/template 实现类似Laravel Blade的布局系统

这是基于Go标准库html/template实现的布局方案,完全匹配你的需求:

项目结构

your-app/
├── templates/
│   ├── main.html   # 带页眉页脚的主布局
│   └── home.html   # 首页内容模板
└── main.go         # 应用入口

1. 主布局文件 templates/main.html

定义基础结构、页眉页脚,并预留内容占位,同时处理标题默认值:

{{define "main"}}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{if .Title}}{{.Title}}{{else}}App Default Title{{end}}</title>
</head>
<body>
    <!-- 固定页眉 -->
    <header style="border-bottom: 1px solid #eee; padding: 1rem;">
        <h1>我的Go Web应用</h1>
        <nav>
            <a href="/" style="margin-right: 1rem;">首页</a>
            <a href="/about">关于我们</a>
        </nav>
    </header>

    <!-- 动态内容占位 -->
    <main style="padding: 2rem;">
        {{block "content" .}}{{end}}
    </main>

    <!-- 固定页脚 -->
    <footer style="border-top: 1px solid #eee; padding: 1rem; text-align: center; margin-top: 2rem;">
        <p>© 2024 我的Go应用 | 保留所有权利</p>
    </footer>
</body>
</html>
{{end}}

2. 首页模板 templates/home.html

实现首页具体内容,继承主布局并传递自定义标题:

{{define "content"}}
<h2>欢迎来到首页</h2>
<p>这是嵌入主布局的首页内容,自动继承了页眉和页脚。</p>
<p>当前页面自定义标题:<strong>{{.Title}}</strong></p>
{{end}}

3. Go 应用代码 main.go

解析模板、处理路由、渲染页面:

package main

import (
	"html/template"
	"net/http"
)

func main() {
	// 解析templates目录下所有HTML模板
	tmpl, err := template.ParseGlob("templates/*.html")
	if err != nil {
		panic("模板解析失败:" + err.Error())
	}

	// 首页路由:传递自定义标题
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 准备模板数据,包含自定义标题
		data := map[string]interface{}{
			"Title": "首页 - 我的Go Web应用",
		}
		// 渲染主布局模板
		if err := tmpl.ExecuteTemplate(w, "main", data); err != nil {
			http.Error(w, "页面渲染失败:"+err.Error(), http.StatusInternalServerError)
		}
	})

	// 测试默认标题的路由
	http.HandleFunc("/about", func(w http.ResponseWriter, r *http.Request) {
		// 不传递Title参数,使用布局默认值
		data := map[string]interface{}{}
		if err := tmpl.ExecuteTemplate(w, "main", data); err != nil {
			http.Error(w, "页面渲染失败:"+err.Error(), http.StatusInternalServerError)
		}
	})

	// 启动服务
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic("服务启动失败:" + err.Error())
	}
}

核心逻辑说明

  • 默认标题实现:通过if-else判断模板数据中的Title字段,不存在则显示默认文本App Default Title。
  • 模板嵌套:主布局用{{block "content" .}}{{end}}定义内容占位,子模板通过{{define "content"}}实现对应内容,渲染主模板时会自动将子模板内容嵌入占位位置。
  • 数据共享:渲染时传入的data对象会被所有模板共享,布局和子页面都能访问其中的参数。

运行测试

  1. 按照项目结构创建文件
  2. 执行go run main.go启动服务
  3. 访问http://localhost:8080:显示自定义标题的首页,包含页眉页脚
  4. 访问http://localhost:8080/about:显示默认标题的页面,同样包含页眉页脚

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 17:40:04