Go中的Html呈现结构和数组

Go中的Html呈现结构和数组,go,Go,I渲染模板: w.Header().Set("Content-type", "text/html") t, _ := template.ParseFiles("index.html") t.Execute(w, &page{Title: "Title"}) 它工作得很好。但是,如果,例如,我有来自数据库的结构呢 我怎样才能用Go渲染它?有什么解决方案吗?Go模板正是为此而设计的。请看以下几个示例: 在这里: 围棋模板正是为此而设计的。请看以下几个示例: 在这里: 它的工作原理没有什

I渲染模板:

w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("index.html")
t.Execute(w, &page{Title: "Title"})
它工作得很好。但是,如果,例如,我有来自数据库的结构呢


我怎样才能用Go渲染它?有什么解决方案吗?

Go模板正是为此而设计的。请看以下几个示例:

在这里:


围棋模板正是为此而设计的。请看以下几个示例:

在这里:


它的工作原理没有什么不同
ExecuteTemplate
接受一个
接口{}
,因此您可以根据需要传递它

我通常会传递一个
map[string]接口{}
,如下所示:

// 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 }}
 ...

希望这能澄清问题。我们有一个有用的示例,其中包括如何使用
html/template

它的工作原理没有什么不同
ExecuteTemplate
接受一个
接口{}
,因此您可以根据需要传递它

我通常会传递一个
map[string]接口{}
,如下所示:

// 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 }}
 ...

希望这能澄清问题。我们有一个有用的示例,其中包括如何使用
html/template

我只是想在我的答案中加上简的文章;)这真的是一个关于
html/template
(甚至
text/template
,因为它们几乎是一样的东西)的优秀资源。我只是想在我的答案中添加Jan的文章;)这确实是一个关于
html/template
(甚至
text/template
,因为它们几乎是一样的东西)的优秀资源。