假设我有一个带有这样的嵌套子模板的模板。游乐场链接
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)
}
}
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)
}
}
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}}
`
怎么做?是否可以?
阿晨1998
收到一只叮咚
蝴蝶刀刀
相关分类