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

Go语言的 text/template 包提供了一种强大而灵活的方式来生成文本内容,适用于配置文件、邮件模板、代码生成等多种场景。它通过将数据结构与模板结合,动态渲染出最终文本。
在 Go 中使用 text/template,首先要定义一个模板字符串,其中可以包含变量、条件判断、循环等控制结构。
核心语法:
{{.}} 表示当前上下文的数据{{.FieldName}} 访问结构体字段或 map 的键{{if .Condition}}...{{end}} 条件判断{{range .Items}}...{{end}} 遍历数组、切片或 map{{template "name" .}} 调用嵌套模板示例:渲染一段用户欢迎信息
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"os"
"text/template"
)</p><p>type User struct {
Name string
Age int
Admin bool
}</p><p>func main() {
const tmpl = <code> Hello {{.Name}}, You are {{.Age}} years old. {{if .Admin}}You have admin privileges.{{else}}You are a regular user.{{end}} </code></p><pre class='brush:php;toolbar:false;'>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}}`
<p>type Server struct {
Name string
Host string
Port int
}</p><p>servers := []Server{
{"web1", "192.168.1.10", 8080},
{"db1", "192.168.1.20", 5432},
}</p><p>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
}
<p>server {
name = "db1"
host = "192.168.1.20"
port = 5432
}</p>对于复杂文本结构,可以使用 define 和 template 指令拆分逻辑,提升可维护性。
示例:构建 HTML 邮件片段
const emailTemplate = `
{{define "greeting"}}Dear {{.Name}},{{end}}
<p>{{define "body"}}
We're excited to announce our new features:
{{range .Features}}</p><ul><li>{{.}}
{{end}}
{{end}}</li></ul><p>{{define "signature"}}Best regards,
The Team
{{end}}</p><p>{{template "greeting" .}}
{{template "body" .}}
{{template "signature"}}
`</p><p>data := map[string]interface{}{
"Name": "Bob",
"Features": []string{"Dark mode", "Offline support", "Faster loading"},
}</p><p>t, _ := template.New("email").Parse(emailTemplate)
t.ExecuteTemplate(os.Stdout, "email", data)
实际开发中,有几点能避免常见问题:
template.Must() 可以简化错误处理,在初始化阶段捕获模板解析错误text/template 而非 html/template
{{.Name | upper}},需注册相应函数ParseGlob 批量加载示例:使用 ParseGlob 加载多个模板文件
t := template.Must(template.ParseGlob("templates/*.tmpl"))
t.ExecuteTemplate(os.Stdout, "index.tmpl", data)
基本上就这些。掌握 text/template 的基本语法和常见模式后,你可以高效地生成各种结构化文本,从简单的提示信息到复杂的配置脚本都能轻松应对。
以上就是Golang如何使用template/text模板生成文本_Golang text模板实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号