使用Golang模板需选择text/template或html/template,后者防XSS;通过Parse解析字符串模板,Execute渲染数据,支持嵌套字段、if/range控制结构;HTML模板自动转义恶意内容;可加载文件模板并用ParseGlob批量解析,ExecuteTemplate执行指定块。

在Golang中使用template渲染模板非常直接,主要通过标准库中的 text/template 和 html/template 实现。前者用于普通文本模板,后者专为HTML设计,具备自动转义功能,防止XSS攻击。
1. 基本用法:定义和渲染模板
你可以通过字符串或文件定义模板,然后将数据注入其中进行渲染。
示例代码:
package mainimport ( "os" "text/template" )
func main() { const templateStr = "Hello, {{.Name}}! You are {{.Age}} years old.\n"
// 定义数据结构 data := struct { Name string Age int }{ Name: "Alice", Age: 30, } // 解析模板 tmpl, err := template.New("greeting").Parse(templateStr) if err != nil { panic(err) } // 渲染到标准输出 err = tmpl.Execute(os.Stdout, data) if err != nil { panic(err) }}
立即学习“go语言免费学习笔记(深入)”;
输出结果:
Hello, Alice! You are 30 years old.2. 使用嵌套字段和条件判断
模板支持访问结构体的嵌套字段、使用if条件、range循环等控制结构。
示例:
const templateStr = `
{{if .User.LoggedIn}}
Welcome back, {{.User.Profile.Name}}!
{{range .User.Notifications}}
- {{.}}
{{end}}
{{else}}
Please log in.
{{end}}
`
对应的数据结构:
data := struct {
User struct {
LoggedIn bool
Profile struct{ Name string }
Notifications []string
}
}{
User: struct {
LoggedIn bool
Profile struct{ Name string }
Notifications []string
}{
LoggedIn: true,
Profile: struct{ Name string }{Name: "Bob"},
Notifications: []string{"New message", "Update available"},
},
}
3. 使用 HTML 模板并防止 XSS
如果你生成的是HTML内容,应使用 html/template,它会自动对数据进行HTML转义。
示例:
package mainimport ( "html/template" "log" "net/http" )
func handler(w http.ResponseWriter, r *http.Request) { tmpl :=
t, err := template.New("page").Parse(tmpl) if err != nil { log.Fatal(err) }Hello, {{.}}
// 即使输入包含HTML,也会被转义 t.Execute(w, "")}
立即学习“go语言免费学习笔记(深入)”;
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
浏览器中实际输出为:
Hello,
页面不会执行脚本,确保安全。
4. 加载模板文件
实际项目中模板通常存放在文件中。可以使用 template.ParseFiles 或 template.ParseGlob。
目录结构:
templates/ header.tmpl content.tmpl footer.tmpl加载多个模板文件:
t, err := template.ParseGlob("templates/*.tmpl")
if err != nil {
log.Fatal(err)
}
也可以定义可复用的块(block):
{{define "header"}}{{end}}
{{define "content"}}Main Content
{{end}}
{{define "footer"}}{{end}}
执行特定块:
t.ExecuteTemplate(os.Stdout, "content", nil)
基本上就这些。掌握解析、数据绑定、控制结构和文件加载,就能灵活使用Go模板。关键是根据场景选择 text/template 还是 html/template,避免安全问题。










