Go语言中text/template包可用于生成文本输出,支持变量插入、条件判断、循环等语法,适用于静态内容或自定义格式文本渲染。通过Parse解析字符串模板或ParseFiles加载文件,结合结构体数据执行渲染;支持多模板组合,使用define定义片段,template指令嵌套;可通过FuncMap注册自定义函数扩展功能,如格式化输出;常用于日志、CLI提示、文档生成等场景,但不适用于需安全转义的HTML输出,此时应选用html/template。

在Go语言中,text/template 包常用于生成文本输出,比如HTML页面、配置文件或邮件内容。虽然它不像
html/template那样具备自动转义功能,但在某些非HTML场景下,
text/template更加灵活。本文将介绍如何使用
text/template实现动态页面渲染的实用方法,尤其适用于生成静态内容或自定义格式文本。
模板定义与基础语法
text/template支持变量插入、条件判断、循环等基本逻辑。你可以把模板写成字符串,也可以从文件加载。
例如,定义一个简单的用户信息模板:
{{.Name}} 的年龄是 {{.Age}}。
{{if .IsAdult}}
已成年
{{else}}
未成年
{{end}}
结构体数据如下:
立即学习“go语言免费学习笔记(深入)”;
type User struct {
Name string
Age int
IsAdult bool
}
通过
template.New().Parse()解析模板并执行:
t := template.New("user")
t, _ = t.Parse(templateStr)
t.Execute(os.Stdout, User{Name: "Alice", Age: 20, IsAdult: true})
从文件加载模板
实际项目中,模板通常保存在独立文件中以便维护。使用
template.ParseFiles()可直接读取文件。
创建文件
user.txt:
姓名:{{.Name}}
状态:{{if gt .Age 18}}已成年{{else}}未成年{{end}}
代码中加载并渲染:
t, err := template.ParseFiles("user.txt")
if err != nil {
log.Fatal(err)
}
t.Execute(os.Stdout, User{Name: "Bob", Age: 17})
组合多个模板
对于复杂输出,可拆分模板为多个片段,并通过
define和
template指令复用。
示例模板文件
layout.txt:
{{define "header"}}=== 系统报告 ==={{end}}
{{define "content"}}
用户:{{.Name}},年龄:{{.Age}}
{{end}}
{{define "footer"}}
生成时间:{{.Time}}
{{end}}
{{template "header"}}
{{template "content" .}}
{{template "footer"}}
渲染时传入包含所有字段的数据:
data := map[string]interface{}{
"Name": "Charlie",
"Age": 25,
"Time": time.Now().Format("2006-01-02"),
}
t, _ := template.ParseFiles("layout.txt")
t.ExecuteTemplate(os.Stdout, "main", data)
自定义函数注入
通过
template.FuncMap注册自定义函数,增强模板表达能力。
例如添加一个格式化年龄的函数:
funcMap := template.FuncMap{
"formatAge": func(age int) string {
return fmt.Sprintf("%d岁", age)
},
}
t := template.New("withFunc").Funcs(funcMap)
t, _ = t.Parse("{{.Name}},{{formatAge .Age}}")
t.Execute(os.Stdout, User{Name: "David", Age: 30})
输出结果为:
David,30岁
基本上就这些。合理使用
text/template能有效解耦数据和输出格式,适合日志生成、CLI工具提示、静态文档渲染等场景。注意避免在安全敏感场景(如HTML)中误用,此时应优先选择
html/template。不复杂但容易忽略的是函数注册顺序和模板嵌套命名规则,建议保持命名清晰统一。










