英文:
Html-rendering structures and arrays in Go
问题
我渲染模板的代码如下:
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("index.html")
t.Execute(w, &page{Title: "Title"})
这段代码可以正常工作。但是如果我有一个来自数据库的结构体,我该如何在Go中进行渲染呢?有什么解决方案吗?
英文:
I render template:
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("index.html")
t.Execute(w, &page{Title: "Title"})
Its works well. But what if, for example, I have structure from database?
How can I render it by Go? Any solutions?
答案1
得分: 3
它的工作方式没有任何区别。ExecuteTemplate
接受一个interface{}
,所以你可以传递任何你想要的东西。
通常我会传递一个map[string]interface{}
,像这样:
// 简写
type M map[string]interface{}
...
err := t.ExecuteTemplate(w, "posts.tmpl", M{
"posts": &posts,
"user": &user,
"errors": []pageErrors,
}
// posts.tmpl
{{ posts.PostTitle }}
{{ with user }}
你好,{{ Name }}!
{{ Email }}
{{ end }}
...
希望这样能澄清问题。Go文档中有一个有用的示例,其中包含如何使用html/template
包的说明。
英文:
It works no differently. ExecuteTemplate
accepts an interface{}
so you can pass it anything you'd like.
I typically pass a map[string]interface{}
like so:
// 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 }}
...
Hope that clarifies. The Go docs have a useful example that includes how to use the html/template
package.
答案2
得分: 2
Go模板正是为此而设计的。请查看以下链接中的一些示例:
http://golangtutorials.blogspot.co.il/2011/06/go-templates.html
以及这里:
http://jan.newmarch.name/golang/template/chapter-template.html
英文:
Go templates are made exactly for that. Have a look at a few examples from here:
http://golangtutorials.blogspot.co.il/2011/06/go-templates.html
and here:
http://jan.newmarch.name/golang/template/chapter-template.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论