Go语言通过text/template包实现高效文本生成,支持变量注入、条件循环控制、自定义函数及模板嵌套。示例展示动态渲染姓名年龄、学生成绩判断、字符串转大写及模板复用,结合html/template可防XSS,适用于HTML页面、配置文件等场景。

Go语言在文本处理方面提供了强大且简洁的工具,尤其适合生成动态文本内容,比如HTML页面、配置文件、邮件模板等。核心支持来自
text/template
Go的
text/template
{{}}基本语法示例:
模板内容:
Hello, {{.Name}}!
You are {{.Age}} years old.
Go代码:
package main
import (
"os"
"text/template"
)
type Person struct {
Name string
Age int
}
func main() {
t := template.New("example")
t, _ = t.Parse("Hello, {{.Name}}! You are {{.Age}} years old.\n")
p := Person{Name: "Alice", Age: 30}
t.Execute(os.Stdout, p)
}
输出:
Hello, Alice! You are 30 years old.
立即学习“go语言免费学习笔记(深入)”;
模板支持
if
range
示例:遍历列表并条件判断
templateStr := `
{{range .}}
{{if gt .Score 80}}
Excellent: {{.Name}} - {{.Score}}
{{else}}
Keep trying: {{.Name}} - {{.Score}}
{{end}}
{{end}}`
type Student struct {
Name string
Score int
}
students := []Student{
{"Bob", 95},
{"Charlie", 70},
}
t, _ := template.New("grades").Parse(templateStr)
t.Execute(os.Stdout, students)
输出:
Excellent: Bob - 95
Keep trying: Charlie - 70
你可以通过
FuncMap
示例:添加一个转大写的函数
funcMap := template.FuncMap{
"upper": strings.ToUpper,
}
t := template.New("withFunc").Funcs(funcMap)
t, _ = t.Parse("Hello, {{upper .}}!")
t.Execute(os.Stdout, "go developer")
输出:
Hello, GO DEVELOPER!
注意:导入
"strings"
strings.ToUpper
大型文本可拆分为多个子模板,使用
define
template
示例:
tpl := `{{define "Greeting"}}Hi, {{.}}{{end}}
{{template "Greeting" "Alice"}}`
t, _ := template.New("main").Parse(tpl)
t.Execute(os.Stdout, nil)
输出:
Hi, Alice
这种机制适合构建可复用的模板片段,如页头、页脚。
基本上就这些。Go的模板系统简单但功能完整,配合
html/template
以上就是Golang text文本处理 模板与转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号