Go语言的text/template包通过{{}}语法将数据与模板结合,支持变量引用、条件判断、循环及自定义函数。使用.访问根对象字段,如{{.Name}};通过{{if}}{{else}}{{end}}实现条件渲染,{{range}}{{end}}遍历数据;可注册FuncMap添加函数扩展功能,如{{mail .Email}};完整示例展示结构体数据渲染为文本,最终输出动态内容。掌握这些即可高效生成HTML、配置文件等文本。

Go语言中的
text/template
在Go模板中,使用双大括号
{{}}.
例如:
Hello, {{.Name}}! You are {{.Age}} years old.
对应的数据结构:
立即学习“go语言免费学习笔记(深入)”;
type Person struct {
Name string
Age int
}
data := Person{Name: "Alice", Age: 25}
渲染时,
.Name
.Age
模板支持
if
range
示例模板:
{{if .LoggedIn}}
Welcome back, {{.UserName}}!
{{else}}
Please log in.
{{end}}
<ul>
{{range .Items}}
<li>{{.}}</li>
{{end}}
</ul>当
LoggedIn
true
range
Items
可以在模板中调用预定义或自定义函数。Go模板允许注册函数映射(FuncMap),扩展模板能力。
示例:
func formatEmail(email string) string {
return "<a href='mailto:" + email + "'>" + email + "</a>"
}
<p>funcMap := template.FuncMap{
"mail": formatEmail,
}</p><p>t := template.New("example").Funcs(funcMap)
t, _ = t.Parse("Contact: {{mail .Email}}")</p>注册一个
{{mail .Email}}下面是一个完整的程序示例:
package main
<p>import (
"os"
"text/template"
)</p><p>type User struct {
Name string
Admin bool
Posts []string
}</p><p>func main() {
const tmpl = `
Hello {{.Name}},
You are {{if .Admin}}an admin{{else}}a regular user{{end}}.</p><p>Your posts:
{{range .Posts}}- {{.}}
{{end}}
`</p><pre class='brush:php;toolbar:false;'>user := User{
Name: "Bob",
Admin: true,
Posts: []string{"First post", "Go templates"},
}
t := template.Must(template.New("user").Parse(tmpl))
t.Execute(os.Stdout, user)}
运行结果:
Hello Bob, You are an admin. <p>Your posts:</p><ul><li>First post</li><li>Go templates
基本上就这些。掌握变量引用、控制结构和自定义函数,就能高效使用Go的文本模板功能。
以上就是Golangtemplate文本模板渲染与使用示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号