2014-03-01 79 views
0

我渲染模板:HTML呈現結構和數組在Go

w.Header().Set("Content-type", "text/html") 
t, _ := template.ParseFiles("index.html") 
t.Execute(w, &page{Title: "Title"}) 

它的效果很好。但是,如果,例如,我有從數據庫結構?

我該如何渲染Go?任何解決方案

回答

3

它的工作原理沒有區別。 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軟件包。