Golang Template 使用教程
Go 的 text/template 和 html/template 是强大的文本模板系统,广泛用于 Web 开发、配置文件生成、代码生成等场景。本教程将系统性介绍 text/template 的核心语法与使用技巧。
1. 快速入门
package main
import (
"os"
"text/template"
)
func main() {
tmpl, _ := template.New("hello").Parse("Hello, {{.Name}}!")
tmpl.Execute(os.Stdout, map[string]string{"Name": "World"})
}
2. 数据绑定
支持任意结构体、map、基本类型。
type Person struct {
Name string
Age int
}
tmpl, _ := template.New("person").Parse("Name: {{.Name}}, Age: {{.Age}}")
tmpl.Execute(os.Stdout, Person{"Tom", 20})
3. 条件语句
{{ if .IsAdmin }}
You are admin.
{{ else if .IsGuest }}
You are guest.
{{ else }}
Unknown user.
{{ end }}
判断相等:
{{ if eq .Role "admin" }}Welcome, Admin.{{ end }}
4. 循环语句
{{ range .Items }}
{{ . }}
{{ else }}
No items found.
{{ end }}
5. 模板嵌套与定义块
{{ define "header" }}<h1>{{.Title}}</h1>{{ end }}
{{ define "content" }}<p>{{.Content}}</p>{{ end }}
{{ template "header" . }}
{{ template "content" . }}
6. 使用函数(内置 + 自定义)
常见内置函数
- eq、ne、lt、gt、and、or、not
- print、printf、len、index
自定义函数
func ToUpper(s string) string {
return strings.ToUpper(s)
}
funcMap := template.FuncMap{
"ToUpper": ToUpper,
}
tmpl := template.New("demo").Funcs(funcMap)
tmpl.Parse("{{ ToUpper .Name }}")
7. 访问 map / slice / struct / pointer
{{ .Map.key }}
{{ index .Slice 0 }}
{{ .Struct.Field }}
{{ .PointerField.Name }}
8. 管道操作(Pipe)
{{ .Name | ToUpper | printf "Hello, %s" }}
9. 嵌套数据结构访问
{{ .User.Name }}
{{ .User.Address.City }}
10. 条件判断值
{{ if .Enabled }}
Feature is enabled.
{{ end }}
11. 模板继承(使用模板文件)
// base.tmpl
{{ define "base" }}
<html>
<body>{{ template "content" . }}</body>
</html>
{{ end }}
// page.tmpl
{{ define "content" }}Hello, {{.Name}}{{ end }}
加载使用:
template.Must(template.ParseFiles("base.tmpl", "page.tmpl"))
tmpl.ExecuteTemplate(os.Stdout, "base", data)
12. 完整示例:条件 + 循环 + 函数 + 嵌套
package main
import (
"os"
"text/template"
)
type Item struct {
Name string
Price int
}
type PageData struct {
Title string
Items []Item
}
tmpl := `
<h1>{{.Title}}</h1>
<ul>
{{ range .Items }}
<li>{{.Name}} - {{.Price}}</li>
{{ else }}
<li>No items</li>
{{ end }}
</ul>
`
func main(){
data := PageData{"Menu", []Item{{"Coffee", 30}, {"Tea", 20}}}
template.Must(template.New("page").Parse(tmpl)).Execute(os.Stdout, data)
}
语法对照表
语法/功能 | 示例 |
---|---|
数据绑定 | {{.Name}} |
条件判断 | {{ if .Admin }} |
逻辑运算 | {{ if and (eq .X 1) .Y }} |
循环遍历 | {{ range .List }} |
嵌套模板 | {{ template "child" . }} |
函数使用 | {{ printf "%s" .Name }} |
自定义函数注册 | template.New(...).Funcs(...).Parse(...) |