Golang 第四章 6.文本和 HTML 模板
Go 提供两个模板包:
text/template → 用于生成纯文本
html/template → 用于生成 HTML,并自动防止 XSS 攻击
创建模板
import (
"os"
"text/template"
)
func main() {
t := template.New("example") // 创建模板对象
t, _ = t.Parse("Hello, {{.Name}}!") // 解析模板文本
data := struct{ Name string }{Name: "Alice"}
t.Execute(os.Stdout, data) // 渲染模板
}输出:
Hello, Alice!模板占位符
{{.FieldName}} → 表示数据结构中字段
. → 当前数据对象
例如:
type Person struct {
Name string
Age int
}
p := Person{Name: "Bob", Age: 25}模板:
t, _ := template.New("p").Parse("Name: {{.Name}}, Age: {{.Age}}")
t.Execute(os.Stdout, p)输出:
Name: Bob, Age: 25条件语句
模板支持 if 条件:
t, _ := template.New("t").Parse(
`{{if .Age}}Age: {{.Age}}{{else}}Age unknown{{end}}`)循环语句
使用 range 遍历切片或数组:
t, _ := template.New("t").Parse(
`{{range .}}Name: {{.Name}}, Age: {{.Age}}
{{end}}`)函数
模板内可以调用 内置函数 或自定义函数:
func upper(s string) string {
return strings.ToUpper(s)
}
t := template.New("t").Funcs(template.FuncMap{
"upper": upper,
}).Parse("{{upper .Name}}")
t.Execute(os.Stdout, Person{Name: "alice"})输出:
ALICEHTML 模板(自动转义)
import "html/template"
t, _ := template.New("html").Parse(`<p>{{.Content}}</p>`)
data := struct{ Content string }{"<script>alert('xss')</script>"}
t.Execute(os.Stdout, data)输出:
<p><script>alert('xss')</script></p>HTML 特殊字符自动转义
防止跨站脚本攻击(XSS)
模板总结用法
创建模板对象 → template.New(name)
解析模板文本 → Parse(text)
渲染 → Execute(output, data)
可添加函数 → Funcs(FuncMap)
HTML 模板自动转义 → html/template



评论