通过html/template包实现Golang模板布局,定义layout.html作为主模板,包含title和content区块;创建index.html和about.html等页面模板分别定义对应区块内容;在Go代码中使用template.ParseGlob加载所有模板,并通过ExecuteTemplate渲染指定模板,实现页面结构复用。

在Golang中使用模板布局,主要是通过html/template包来实现页面结构复用,比如公共的头部、底部或侧边栏。常见的做法是定义一个主布局模板(layout),然后让其他页面内容填充到指定区域,实现类似“母版页”的效果。
创建一个基础的HTML布局文件,比如 layout.html,包含通用结构和可替换的内容区块:
{{define "layout"}} <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>{{template "title" .}}</title> </head> <body> <header> <h1>网站标题</h1> <nav><a href="/">首页</a> | <a href="/about">关于</a></nav> </header><main>
{{template "content" .}}
</main>
<footer>
<p>© 2024 版权所有</p>
</footer></body> </html> {{end}}
接着创建页面模板,如 index.html,它将继承并填充 layout 中的区块:
立即学习“go语言免费学习笔记(深入)”;
{{define "title"}}首页 - 我的网站{{end}}{{define "content"}} <h2>欢迎来到首页</h2> <p>当前时间:{{.Now.Format "2006-01-02 15:04:05"}}</p> {{end}}
再比如 about.html:
{{define "title"}}关于我们 - 我的网站{{end}}{{define "content"}} <h2>关于我们</h2> <p>这是一个简单的Go模板示例项目。</p> {{end}}
使用Golang程序加载模板,并将数据传入进行渲染:
package main
import (
"html/template"
"net/http"
"time"
)
var templates = template.Must(template.ParseGlob("templates/*.html"))
func renderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
err := templates.ExecuteTemplate(w, "layout", data)
if err != nil {
http.Error(w, "无法渲染模板", http.StatusInternalServerError)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := struct {
Now time.Time
}{
Now: time.Now(),
}
renderTemplate(w, "index", data)
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "about", nil)
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/about", aboutHandler)
// 假设模板文件放在 templates/ 目录下
http.ListenAndServe(":8080", nil)
}注意:template.ParseGlob("templates/*.html") 会加载目录下所有模板文件,只要它们使用了 {{define}} 定义命名区块,就能被正确识别和引用。
当调用 ExecuteTemplate 并指定模板名为 "layout" 时,Go会执行 layout 模板中的结构,同时查找当前模板集中是否有名为 "title" 和 "content" 的区块,并将其插入对应位置。
基本上就这些。通过这种方式,你可以轻松实现多页面共享布局,保持代码整洁且易于维护。
以上就是如何在Golang中使用模板布局_Golang 模板布局实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号