模板渲染
1. 基本模板语法
Go的html/template包提供了安全的HTML模板渲染:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>{{.Title}}</h1>
<p>当前时间: {{.Now.Format "2006-01-02 15:04:05"}}</p>
{{if .IsAdmin}}
<p>欢迎管理员!</p>
{{else}}
<p>欢迎普通用户!</p>
{{end}}
<ul>
{{range .Items}}
<li>{{.}}</li>
{{end}}
</ul>
</body>
</html>
func renderTemplate(w http.ResponseWriter) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := struct {
Title string
Now time.Time
IsAdmin bool
Items []string
}{
Title: "我的网页",
Now: time.Now(),
IsAdmin: true,
Items: []string{"Go", "Python", "JavaScript"},
}
tmpl.Execute(w, data)
}
2. 模板继承
定义基础模板
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{template "title" .}}</title>
</head>
<body>
<header>网站标题</header>
{{template "content" .}}
<footer>版权信息 © 2023</footer>
</body>
</html>
继承基础模板
<!-- templates/home.html -->
{{define "title"}}首页{{end}}
{{define "content"}}
<h1>欢迎来到首页</h1>
<p>这是首页内容...</p>
{{end}}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl := template.Must(template.ParseFiles("templates/base.html", "templates/home.html"))
tmpl.ExecuteTemplate(w, "base", nil)
})
http.ListenAndServe(":8080", nil)
}
3. 自定义模板函数
func main() {
// 创建自定义函数
funcMap := template.FuncMap{
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
"add": func(a, b int) int {
return a + b
},
}
// 创建模板并注册函数
tmpl := template.New("").Funcs(funcMap)
tmpl = template.Must(tmpl.Parse(`
<p>日期: {{.Date | formatDate}}</p>
<p>1 + 2 = {{add 1 2}}</p>
`))
data := struct {
Date time.Time
}{
Date: time.Now(),
}
tmpl.Execute(os.Stdout, data)
}
4. 与Gin框架集成
Gin内置支持HTML模板渲染:
func main() {
r := gin.Default()
// 加载模板文件
r.LoadHTMLGlob("templates/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Gin模板示例",
"items": []string{"Go", "Gin", "Template"},
})
})
r.Run(":8080")
}
5. 模板最佳实践
- 安全性:
html/template会自动转义HTML,防止XSS攻击 - 性能:在初始化时解析模板,而不是每次请求时解析
- 组织:合理组织模板目录结构,如:
templates/ ├── layouts/ │ ├── base.html │ └── admin.html ├── partials/ │ ├── header.html │ └── footer.html └── pages/ ├── home.html └── about.html - 调试:使用
template.Must捕获模板解析错误
提示:模板系统是前后端分离的轻量级替代方案,适合需要服务器端渲染的场景。
