【发布时间】:2026-01-14 17:05:02
【问题描述】:
假设我有一个像这样嵌套子模板的模板。 playground link
package main
import (
"os"
"text/template"
)
type Person struct {
FirstName string
SecondName string
}
type Document struct {
DocName string
People []Person
}
const document = `
Document name: {{.DocName}}
{{range $person:=.People}}
{{template "person" $person}}
{{end}}
{{- define "person"}}
Person name is: {{.FirstName}} {{.SecondName}}
{{end}}
`
func main() {
d := Document{
DocName: "first try",
People: []Person{
{"Brian", "Kernighan"},
{"Dennis", "Ritchie"},
},
}
t := template.Must(template.New("document").Parse(document))
err := t.Execute(os.Stdout, d)
if err != nil {
panic(err)
}
}
一切正常,但现在我想设置一些文档范围的变量来改变所有模板及其子模板中的行为。像这样(不工作,恐慌)。 playground link
type Person struct {
FirstName string
SecondName string
}
type Document struct {
DocName string
People []Person
SwitchNameOrder bool
}
const document = `
Document name: {{.DocName}}
{{range $person:=.People}}
{{template "person" $person}}
{{end}}
{{- define "person"}}
{{if $.SwitchNameOrder}} // <---- panic here
Person name is: {{.SecondName}} {{.FirstName}}
{{else}}
Person name is: {{.FirstName}} {{.SecondName}}
{{end}}
{{end}}
`
怎么做?有可能吗?
【问题讨论】:
标签: go go-templates