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

在Go语言中,text/template 包提供了一套强大且灵活的模板渲染机制,适用于生成文本输出,比如HTML页面、配置文件、邮件内容等。它通过将数据与模板结合,动态生成最终结果。下面通过实战方式带你掌握Golang中如何使用 text/template 实现模板渲染。
模板的基本用法是定义一个包含占位符的字符串或文件,然后将数据注入其中进行渲染。
占位符使用双大括号 { { }} 表示,其中点(.)代表传入的数据对象。
示例代码:
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"os"
"text/template"
)</p><p>func main() {
const templateStr = "Hello, { {.Name}}! You are { {.Age}} years old.\n"</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">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}}
`
<p>type User struct {
Name string
Age int
}</p><p>users := []User{
{Name: "Bob", Age: 17},
{Name: "Charlie", Age: 20},
}</p><p>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
}
<p>type Profile struct {
Name string
Age int
Addr Address
}</p><p>const profileTmpl = "Name: { {.Name}}, Lives in { {.Addr.City}}, { {.Addr.State}}\n"</p><p>profile := Profile{
Name: "David",
Age: 30,
Addr: Address{City: "Beijing", State: "China"},
}</p><p>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
},
}
<p>tmpl := template.New("demo").Funcs(funcMap)
tmpl, _ = tmpl.Parse(<code> Name: { {.Name | upper}} Double Age: { {.Age | double}} </code>)</p><p>data := map[string]interface{}{
"Name": "eve",
"Age": 22,
}
tmpl.Execute(os.Stdout, data)
输出:
Name: EVE
Double Age: 44
管道符号 | 可以链式调用函数,如 { {.Text | trim | upper }}。
基本上就这些核心用法。掌握变量绑定、流程控制、嵌套结构和自定义函数后,你就能在项目中灵活使用 text/template 渲染各类文本内容了。不复杂但容易忽略细节,建议多写几个小例子加深理解。
以上就是Golang如何实现模板渲染_Golang text/template模板渲染实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号