在Go语言中渲染HTML结构和数组的方法

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年3月2日 05:09:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/22120404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定