英文:
How do you pass structs to subtemplates in go?
问题
我正在尝试理解如何在Go中多次使用相同的模板,传递不同的结构体。
这是我尝试过的代码:
import (
"fmt"
"html/template"
"os"
)
type person struct {
id int
name string
phone string
}
type page struct {
p1 person
p2 person
}
func main() {
p1 := person{1, "Peter", "1001"}
p2 := person{2, "Mary", "1002"}
p := page{p1, p2}
fmt.Println(p)
t := template.Must(template.New("foo").Parse(`
{{define "s1"}}
<span id="{{.id}}">{{.name}} {{.phone}}</span>
{{end}}
{{template "s1" .p1}}{{template "s1" .p2}}
`))
t.Execute(os.Stdout, p)
}
但它没有按预期工作:
panic: template: foo:5: unexpected "{" in template clause
预期的输出是:
Peter 1001Mary 1002
英文:
I am trying to understand how to use the same template in Go several time passing different structs.
This is what I have tried:
import (
"fmt"
"html/template"
"os"
)
type person struct {
id int
name string
phone string
}
type page struct {
p1 person
p2 person
}
func main() {
p1 := person{1, "Peter", "1001"}
p2 := person{2, "Mary", "1002"}
p := page{p1, p2}
fmt.Println(p)
t := template.Must(template.New("foo").Parse(`
{{define "s1"}}
<span id="{{.id}}">{{.name}} {{.phone}}</span>
{{end}}
{{template "s1" {{.p1}}}}{{template "s1" {{.p2}}}}
`))
t.Execute(os.Stdout, p)
}
But it does not work as expected:
panic: template: foo:5: unexpected "{" in template clause
The expected output is:
<span id="1">Peter 1001</span><span id="2">Mary 1002</span>
答案1
得分: 2
当你调用模板函数时,你需要提供两个参数(用空格分隔):
- 一个已定义的模板名称("s1")
- 你的对象:在你的情况下是.p1
所以这是一个适用于你的工作模板:
t := template.Must(template.New("foo").Parse(`
{{ define "s1" }}
<span id="{{ .id }}">{{.name}} {{ .phone }}</span>
{{ end }}
{{ template "s1" .p1 }}
{{ template "s1" .p2 }}
`))
}
英文:
When you call the template function, you give 2 arguments (separated by a space):
- A defined template name ("s1")
- You object: .p1 in your case
So here is a working template in your case:
t := template.Must(template.New("foo").Parse(`
{{ define "s1" }}
<span id="{{ .id }}">{{.name}} {{ .phone }}</span>
{{ end }}
{{ template "s1" .p1 }}
{{ template "s1" .p2 }}
`))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论