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

在Golang中使用 text/template 渲染模板非常实用,尤其适用于生成文本输出,如日志、配置文件、邮件内容等。它通过将数据结构与模板结合,动态生成所需文本。
使用 text/template 包的第一步是创建一个模板字符串,然后将数据注入其中。
示例:
package main
<p>import (
"os"
"text/template"
)</p><p>type User struct {
Name string
Age int
}</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;">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}} 是模板中的占位符,. 表示当前数据上下文。
模板支持 if、range 等控制逻辑,便于处理复杂数据。
示例:使用 if 判断和 range 遍历切片
const templateStr = `
{{if .Active}}
Status: Active
{{else}}
Status: Inactive
{{end}}
<p>Friends:
{{range .Friends}}- {{.}}
{{end}}
`</p><p>type Person struct {
Active bool
Friends []string
}</p><p>person := Person{
Active: true,
Friends: []string{"Bob", "Charlie", "Dana"},
}</p><p>tmpl := template.Must(template.New("status").Parse(templateStr))
tmpl.Execute(os.Stdout, person)
输出:
立即学习“go语言免费学习笔记(深入)”;
Status: Active <p>Friends:</p><ul><li>Bob</li><li>Charlie</li><li>Dana
你可以注册自定义函数,供模板内部调用。
示例:添加一个转大写的函数
funcMap := template.FuncMap{
"upper": strings.ToUpper,
}
<p>tmpl := template.New("withFunc").Funcs(funcMap)
tmpl, _ = tmpl.Parse("Hello, {{.Name | upper}}!\n")</p><p>user := User{Name: "bob"}
tmpl.Execute(os.Stdout, user)
输出:Hello, BOB!
| 是管道操作符,将前面的值传给后面的函数。
可以定义多个模板片段,并通过 template 动作嵌入。
const mainTmpl = `
{{define "Greeting"}}
Hello, {{.Name}}
{{end}}
<p>{{define "Info"}}
You are {{.Age}} years old.
{{end}}</p><p>{{template "Greeting" .}}
{{template "Info" .}}
`</p><p>tmpl := template.Must(template.New("combined").Parse(mainTmpl))
tmpl.Execute(os.Stdout, User{Name: "Eve", Age: 30})
这样可以实现模板复用,适合生成结构化文本。
基本上就这些。只要掌握数据绑定、控制结构和函数扩展,就能灵活使用 text/template 生成各种文本内容。
以上就是如何在Golang中使用text/template渲染模板的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号