Go语言text/template包通过{ {}}占位符绑定数据,支持变量渲染、if条件判断、range循环遍历、嵌套字段访问,并可使用Funcs注册自定义函数,结合管道符号实现灵活的文本生成。

在Go语言中,text/template 包提供了一套强大且灵活的模板渲染机制,适用于生成文本输出,比如HTML页面、配置文件、邮件内容等。它通过将数据与模板结合,动态生成最终结果。下面通过实战方式带你掌握Golang中如何使用 text/template 实现模板渲染。
基础语法与数据绑定
模板的基本用法是定义一个包含占位符的字符串或文件,然后将数据注入其中进行渲染。
占位符使用双大括号 { { }} 表示,其中点(.)代表传入的数据对象。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package mainimport ( "os" "text/template" )
func main() { const templateStr = "Hello, { {.Name}}! You are { {.Age}} years old.\n"
type Person struct { Name string Age int } person := Person{Name: "Alice", Age: 25} tmpl, _ := template.New("greeting").Parse(templateStr) tmpl.Execute(os.Stdout, person)}
输出结果:
Hello, Alice! You are 25 years old.条件判断与循环控制
模板支持基本的逻辑控制,如 if 判断和 range 遍历,适合处理复杂结构数据。
使用 { {if .Condition}} 进行条件渲染,{ {range .Slice}} 遍历切片或map。
示例:展示用户列表并判断是否成年
const userTemplate = ` { {range .}} Name: { {.Name}} { {if ge .Age 18}} Status: Adult { {else}} Status: Minor { {end}} { {end}} `type User struct { Name string Age int }
users := []User{ {Name: "Bob", Age: 17}, {Name: "Charlie", Age: 20}, }
tmpl, _ := template.New("users").Parse(userTemplate) tmpl.Execute(os.Stdout, users)
注意:
ge是“大于等于”的内置函数,还有eq、lt、le、ne等比较操作。嵌套结构与字段访问
模板可以访问结构体的嵌套字段,语法为 { {.Field.SubField}}。
示例:渲染带地址信息的用户资料
type Address struct { City string State string }type Profile struct { Name string Age int Addr Address }
const profileTmpl = "Name: { {.Name}}, Lives in { {.Addr.City}}, { {.Addr.State}}\n"
profile := Profile{ Name: "David", Age: 30, Addr: Address{City: "Beijing", State: "China"}, }
tmpl, _ := template.New("profile").Parse(profileTmpl) tmpl.Execute(os.Stdout, profile)
自定义函数模板
可以通过 Funcs 方法注册自定义函数,扩展模板能力。
示例:添加格式化时间或转大写函数
funcMap := template.FuncMap{ "upper": strings.ToUpper, "double": func(n int) int { return n * 2 }, }tmpl := template.New("demo").Funcs(funcMap) tmpl, _ = tmpl.Parse(
Name: { {.Name | upper}} Double Age: { {.Age | double}})data := map[string]interface{}{ "Name": "eve", "Age": 22, } tmpl.Execute(os.Stdout, data)
输出:
Name: EVE
Double Age: 44管道符号 | 可以链式调用函数,如 { {.Text | trim | upper }}。
基本上就这些核心用法。掌握变量绑定、流程控制、嵌套结构和自定义函数后,你就能在项目中灵活使用 text/template 渲染各类文本内容了。不复杂但容易忽略细节,建议多写几个小例子加深理解。










