我試圖了解如何在 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
預期的輸出是:
<span id="1">Peter 1001</span><span id="2">Mary 1002</span>
uj5u.com熱心網友回復:
當您呼叫模板函式時,您提供 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 }}
`))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473703.html
下一篇:自定義模板類的C 向量作為成員
