Go 模板语法
2025/5/14大约 2 分钟componenttemplatesyntax
概述
Go 的 text/template
包提供了一种功能强大且灵活的方式来生成文本输出。以下是 text/template
使用的基本语法规则:
- 模板定义: 模板通常定义在
.tmpl
或.tpl
文件中。 - 动作: 动作用
{{
和}}
包围,用于在模板中插入数据或执行逻辑。 - 变量: 变量使用点号
.
访问,例如{{.Name}}
。 - 注释: 以
{{/*
开头,以*/}}
结尾。
动作(Action)
动作是模板语言中的核心,使用 {{ }}
包裹,例如:
{{.}} // 当前对象
{{.Field}} // 当前对象的字段
{{if .Condition}} // 条件语句
// 执行某些操作
{{end}}
{{range .Items}} // 循环
{{.}}
{{end}}
变量声明和赋值
你可以在模板中声明和赋值变量:
{{ $name := "World" }}
Hello, {{ $name }}!
条件语句
模板语言支持条件语句:
{{if .Condition}}
True
{{else}}
False
{{end}}
循环
range
可以用来迭代数组、切片、映射等:
{{range .Items}}
Item: {{.}}
{{end}}
获取 map 的 key 和 value
{{range $key, $val := .Map}}
print("{{$key}}", "{{$val}}")
{{end}}
引用上一层级的变量值
{{range .Services}}
print("{{.ServiceName}}")
{{ $serviceName := .ServiceName }}
{{range .Methods}}
print("{{$serviceName}}") // 这里在内层引用上一层 Service 结构体的 ServiceName
{{end}}
{{end}}
函数
模板中可以调用预定义的函数或自定义函数:
// 定义一个结构体作为模板的数据源
type User struct {
Name string
Age int
Email string
}
// 自定义函数示例
func getCurrentYear() int {
return time.Now().Year()
}
func defineTemplate() {
// 定义模板
tmpl := template.New("example")
// 添加预定义函数
tmpl = tmpl.Funcs(template.FuncMap{
"uppercase": strings.ToUpper, // 使用标准库中的函数
"now": time.Now,
})
// 添加自定义函数
tmpl = tmpl.Funcs(template.FuncMap{
"year": getCurrentYear,
})
// 定义模板内容
const tmplText = `
Hello {{.Name}},
Your email is: {{.Email}}
Your age in {{now | year}} will be {{add .Age 1}}.
And here's your name in uppercase: {{uppercase .Name}}
`
// 解析模板内容
)
删除空格和换行
在 text/template
中,{{-
和 -}}
的作用是去除模板标签周围的空白字符。具体来说,它们可以删除标签左边或右边的空白符(如空格、换行符)。
{{- range .Items}}
{{.Name}}
{{- end}}