[英]Pass multiple structs into ExecuteTemplate in Go - best practice
Currently I am passing multiple structs into ExecuteTemplate, but is there a more efficient, more concise, or different way to do this?目前我正在将多个结构传递给 ExecuteTemplate,但有没有更有效、更简洁或不同的方法来做到这一点?
Go Go
type user struct {
Username string
Password string
}
type meta struct {
Title string
Content string
}
func index(w http.ResponseWriter, req *http.Request) {
u := getUser(w, req)
m := meta{
Title: "Homepage",
Content: "Homepage meta content",
}
users := []user{u}
metas := []meta{m}
data := struct {
User []user
Meta []meta
}{
users,
metas,
}
err := tpl.ExecuteTemplate(w, "index.html", data)
if err != nil {
log.Fatalln(err)
}
}
HTML HTML
{{range .Meta}}
{{.Title}}
{{.Content}}
{{end}}
The same can be achieved more concisely using a map:使用 map 可以更简洁地实现相同的目的:
err := tpl.ExecuteTemplate(w, "index.html", map[string]interface{}{"User":[]user{u},
"Meta":[]meta{m}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.