Go语言中text/template包可用于生成文本输出,支持变量插入、条件判断、循环等语法,适用于静态内容或自定义格式文本渲染。通过Parse解析字符串模板或ParseFiles加载文件,结合结构体数据执行渲染;支持多模板组合,使用define定义片段,template指令嵌套;可通过FuncMap注册自定义函数扩展功能,如格式化输出;常用于日志、CLI提示、文档生成等场景,但不适用于需安全转义的HTML输出,此时应选用html/template。

在Go语言中,text/template 包常用于生成文本输出,比如HTML页面、配置文件或邮件内容。虽然它不像
html/template
text/template
text/template
text/template
例如,定义一个简单的用户信息模板:
{{.Name}} 的年龄是 {{.Age}}。
{{if .IsAdult}}
已成年
{{else}}
未成年
{{end}}结构体数据如下:
立即学习“go语言免费学习笔记(深入)”;
type User struct {
Name string
Age int
IsAdult bool
}通过
template.New().Parse()
t := template.New("user")
t, _ = t.Parse(templateStr)
t.Execute(os.Stdout, User{Name: "Alice", Age: 20, IsAdult: true})实际项目中,模板通常保存在独立文件中以便维护。使用
template.ParseFiles()
创建文件
user.txt
姓名:{{.Name}}
状态:{{if gt .Age 18}}已成年{{else}}未成年{{end}}代码中加载并渲染:
t, err := template.ParseFiles("user.txt")
if err != nil {
log.Fatal(err)
}
t.Execute(os.Stdout, User{Name: "Bob", Age: 17})</font>
对于复杂输出,可拆分模板为多个片段,并通过
define
template
示例模板文件
layout.txt
{{define "header"}}=== 系统报告 ==={{end}}
{{define "content"}}
用户:{{.Name}},年龄:{{.Age}}
{{end}}
{{define "footer"}}
生成时间:{{.Time}}
{{end}}
{{template "header"}}
{{template "content" .}}
{{template "footer"}}渲染时传入包含所有字段的数据:
data := map[string]interface{}{
"Name": "Charlie",
"Age": 25,
"Time": time.Now().Format("2006-01-02"),
}
t, _ := template.ParseFiles("layout.txt")
t.ExecuteTemplate(os.Stdout, "main", data)</font>
通过
template.FuncMap
例如添加一个格式化年龄的函数:
funcMap := template.FuncMap{
"formatAge": func(age int) string {
return fmt.Sprintf("%d岁", age)
},
}
t := template.New("withFunc").Funcs(funcMap)
t, _ = t.Parse("{{.Name}},{{formatAge .Age}}")
t.Execute(os.Stdout, User{Name: "David", Age: 30})</font>
输出结果为:
David,30岁
基本上就这些。合理使用
text/template
html/template
以上就是Golangtext/template实现动态页面渲染实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号