我渲染模板:HTML呈現結構和數組在Go
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("index.html")
t.Execute(w, &page{Title: "Title"})
它的效果很好。但是,如果,例如,我有從數據庫結構?
我該如何渲染Go?任何解決方案
我渲染模板:HTML呈現結構和數組在Go
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("index.html")
t.Execute(w, &page{Title: "Title"})
它的效果很好。但是,如果,例如,我有從數據庫結構?
我該如何渲染Go?任何解決方案
它的工作原理沒有區別。 ExecuteTemplate
接受interface{}
,所以你可以通過任何你想要的。
我通常通過一個map[string]interface{}
像這樣:
// Shorthand
type M map[string]interface{}
...
err := t.ExecuteTemplate(w, "posts.tmpl", M{
"posts": &posts,
"user": &user,
"errors": []pageErrors,
}
// posts.tmpl
{{ posts.PostTitle }}
{{ with user }}
Hello, {{ Name }}!
{{ Email }}
{{ end }}
...
希望有所澄清。 Go docs有一個有用的示例,其中包括如何使用html/template
軟件包。
我只是想將Jan的文章加入我的回答;)它確實是'html/template'(甚至是'text/template',因爲它們幾乎是相同的東西)的優秀資源。 – elithrar