Go语言的text/template包通过数据与模板结合实现动态文本生成,支持变量、条件、循环等语法,适用于配置文件、邮件模板等场景。

Go语言的 text/template 包提供了一种强大而灵活的方式来生成文本内容,适用于配置文件、邮件模板、代码生成等多种场景。它通过将数据结构与模板结合,动态渲染出最终文本。
模板的基本语法和使用方式
在 Go 中使用 text/template,首先要定义一个模板字符串,其中可以包含变量、条件判断、循环等控制结构。
核心语法:
-
{{.}}表示当前上下文的数据 -
{{.FieldName}}访问结构体字段或 map 的键 -
{{if .Condition}}...{{end}}条件判断 -
{{range .Items}}...{{end}}遍历数组、切片或 map -
{{template "name" .}}调用嵌套模板
示例:渲染一段用户欢迎信息
立即学习“go语言免费学习笔记(深入)”;
package mainimport ( "os" "text/template" )
type User struct { Name string Age int Admin bool }
func main() { const tmpl =
Hello {{.Name}}, You are {{.Age}} years old. {{if .Admin}}You have admin privileges.{{else}}You are a regular user.{{end}}user := User{Name: "Alice", Age: 28, Admin: true} t := template.Must(template.New("welcome").Parse(tmpl)) t.Execute(os.Stdout, user)}
输出结果:
Hello Alice, You are 28 years old. You have admin privileges.处理列表和循环遍历
当需要渲染多个条目时,比如生成日志摘要或配置项列表,
range是关键。示例:生成服务器配置列表
const serverTmpl = `# Generated server list {{range .}}server { name = "{{.Name}}" host = "{{.Host}}" port = {{.Port}} } {{end}}`type Server struct { Name string Host string Port int }
servers := []Server{ {"web1", "192.168.1.10", 8080}, {"db1", "192.168.1.20", 5432}, }
t := template.Must(template.New("servers").Parse(serverTmpl)) t.Execute(os.Stdout, servers)
输出为:
# Generated server list server { name = "web1" host = "192.168.1.10" port = 8080 }server { name = "db1" host = "192.168.1.20" port = 5432 }
定义和调用命名模板(嵌套复用)
对于复杂文本结构,可以使用
define和template指令拆分逻辑,提升可维护性。示例:构建 HTML 邮件片段
const emailTemplate = ` {{define "greeting"}}Dear {{.Name}},{{end}}{{define "body"}} We're excited to announce our new features: {{range .Features}}
- {{.}} {{end}} {{end}}
{{define "signature"}}Best regards, The Team {{end}}
{{template "greeting" .}} {{template "body" .}} {{template "signature"}} `
data := map[string]interface{}{ "Name": "Bob", "Features": []string{"Dark mode", "Offline support", "Faster loading"}, }
t, _ := template.New("email").Parse(emailTemplate) t.ExecuteTemplate(os.Stdout, "email", data)
实用技巧与注意事项
实际开发中,有几点能避免常见问题:
- 使用
template.Must()可以简化错误处理,在初始化阶段捕获模板解析错误 - 模板默认会对 HTML 特殊字符进行转义,若用于非 HTML 文本(如配置文件),应使用
text/template而非html/template - 可以通过自定义函数添加模板功能,例如格式化时间、拼接字符串等
- 模板支持管道操作,如
{{.Name | upper}},需注册相应函数 - 模板文件过多时,可用
ParseGlob批量加载
示例:使用 ParseGlob 加载多个模板文件
t := template.Must(template.ParseGlob("templates/*.tmpl"))
t.ExecuteTemplate(os.Stdout, "index.tmpl", data)
基本上就这些。掌握 text/template 的基本语法和常见模式后,你可以高效地生成各种结构化文本,从简单的提示信息到复杂的配置脚本都能轻松应对。










