Golang的text/template用于动态生成文本,支持数据绑定、条件循环控制、自定义函数及模板嵌套。通过{{.}}引用数据,if/range实现逻辑判断与遍历,FuncMap注册函数如upper,define/template实现模块化复用,适用于配置、日志等文本生成场景。

在Golang中使用 text/template 渲染模板非常实用,尤其适用于生成文本输出,如日志、配置文件、邮件内容等。它通过将数据结构与模板结合,动态生成所需文本。
1. 基本用法:定义模板并渲染数据
使用 text/template 包的第一步是创建一个模板字符串,然后将数据注入其中。
示例:
package mainimport ( "os" "text/template" )
type User struct { Name string Age int }
func main() { const templateStr = "Hello, {{.Name}}! You are {{.Age}} years old.\n"
tmpl := template.Must(template.New("user").Parse(templateStr)) user := User{Name: "Alice", Age: 25} tmpl.Execute(os.Stdout, user)}
输出:
立即学习“go语言免费学习笔记(深入)”;
Hello, Alice! You are 25 years old.
{{.Name}}和{{.Age}}是模板中的占位符,.表示当前数据上下文。2. 控制结构:条件判断与循环
模板支持
if、range等控制逻辑,便于处理复杂数据。示例:使用 if 判断和 range 遍历切片
const templateStr = ` {{if .Active}} Status: Active {{else}} Status: Inactive {{end}}Friends: {{range .Friends}}- {{.}} {{end}} `
type Person struct { Active bool Friends []string }
person := Person{ Active: true, Friends: []string{"Bob", "Charlie", "Dana"}, }
tmpl := template.Must(template.New("status").Parse(templateStr)) tmpl.Execute(os.Stdout, person)
输出:
立即学习“go语言免费学习笔记(深入)”;
Status: ActiveFriends:
- Bob
- Charlie
- Dana
3. 设置函数模板:自定义模板函数
你可以注册自定义函数,供模板内部调用。
示例:添加一个转大写的函数
funcMap := template.FuncMap{ "upper": strings.ToUpper, }tmpl := template.New("withFunc").Funcs(funcMap) tmpl, _ = tmpl.Parse("Hello, {{.Name | upper}}!\n")
user := User{Name: "bob"} tmpl.Execute(os.Stdout, user)
输出:
Hello, BOB!|是管道操作符,将前面的值传给后面的函数。4. 模板嵌套与组合
可以定义多个模板片段,并通过
template动作嵌入。const mainTmpl = ` {{define "Greeting"}} Hello, {{.Name}} {{end}}{{define "Info"}} You are {{.Age}} years old. {{end}}
{{template "Greeting" .}} {{template "Info" .}} `
tmpl := template.Must(template.New("combined").Parse(mainTmpl)) tmpl.Execute(os.Stdout, User{Name: "Eve", Age: 30})
这样可以实现模板复用,适合生成结构化文本。
基本上就这些。只要掌握数据绑定、控制结构和函数扩展,就能灵活使用 text/template 生成各种文本内容。










