首页 > 后端开发 > Golang > 正文

如何在Golang中使用text/template渲染模板

P粉602998670
发布: 2025-10-22 17:20:02
原创
923人浏览过
Golang的text/template用于动态生成文本,支持数据绑定、条件循环控制、自定义函数及模板嵌套。通过{{.}}引用数据,if/range实现逻辑判断与遍历,FuncMap注册函数如upper,define/template实现模块化复用,适用于配置、日志等文本生成场景。

如何在golang中使用text/template渲染模板

在Golang中使用 text/template 渲染模板非常实用,尤其适用于生成文本输出,如日志、配置文件、邮件内容等。它通过将数据结构与模板结合,动态生成所需文本。

1. 基本用法:定义模板并渲染数据

使用 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语言免费学习笔记(深入)”;

AiPPT模板广场
AiPPT模板广场

AiPPT模板广场-PPT模板-word文档模板-excel表格模板

AiPPT模板广场 147
查看详情 AiPPT模板广场

Hello, Alice! You are 25 years old.
登录后复制

{{.Name}}{{.Age}} 是模板中的占位符,. 表示当前数据上下文。

2. 控制结构:条件判断与循环

模板支持 ifrange 等控制逻辑,便于处理复杂数据。

示例:使用 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
登录后复制

3. 设置函数模板:自定义模板函数

你可以注册自定义函数,供模板内部调用。

示例:添加一个转大写的函数

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!

| 是管道操作符,将前面的值传给后面的函数。

4. 模板嵌套与组合

可以定义多个模板片段,并通过 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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号