Go语言的text/template包提供数据驱动的文本生成功能,支持变量插入{{.Field}}、条件判断{{if}}、循环遍历{{range}}及函数调用,可通过FuncMap注册自定义函数,支持模板嵌套define与template,适用于生成HTML、配置文件等内容,强调安全性与简洁性。

Go语言的
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 templateText = "Hello, {{.Name}}! You are {{.Age}} years old.\n"</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">tmpl, err := template.New("greeting").Parse(templateText)
if err != nil {
panic(err)
}
user := User{Name: "Alice", Age: 25}
tmpl.Execute(os.Stdout, user)}
输出结果为:
Hello, Alice! You are 25 years old.
立即学习“go语言免费学习笔记(深入)”;
其中
{{.Name}}{{.Age}}模板支持基本的逻辑控制,如
if
range
例如,处理用户列表并判断年龄是否成年:
const templateText = `
{{range .}}
- Name: {{.Name}}
{{if ge .Age 18}}
Status: Adult
{{else}}
Status: Minor
{{end}}
{{end}}
`
使用
range
if
ge
eq
ne
lt
gt
le
ge
除了字段访问,模板还支持调用函数或方法。可以注册自定义函数到模板中。
例如,添加一个格式化函数:
funcMap := template.FuncMap{
"title": strings.Title,
}
<p>tmpl := template.New("demo").Funcs(funcMap)
然后在模板中使用:
{{title .Name}}也可以为数据类型定义方法,模板会自动识别并调用。
对于大型文本生成任务,可以使用
define
template
例如:
{{define "header"}}<h1>{{.Title}}</h1>{{end}}
<p>{{define "main"}}
{{template "header" .}}
<p>{{.Content}}</p>
{{end}}
通过
template
基本上就这些。Go的文本模板设计简洁,强调安全性与可预测性,不鼓励在模板中写复杂逻辑。合理使用变量、控制结构和函数扩展,就能高效完成大多数文本生成任务。
以上就是Golang的text文本处理 模板与转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号