Golang模板 - 如何使模板?

问题描述 投票:9回答:1

一个带有三个子模板的布局模板。

的layout.html

<html>
  <body>
    {{template "tags"}}

    {{template "content"}}

    {{template "comment"}}
  </body>
</html>

tags.html

{{define "tags"}}
<div>
    {{.Name}}
<div>
{{end}}

content.html

{{define "content"}}
<div>
   <p>{{.Title}}</p>
   <p>{{.Content}}</p>
</div>
{{end}}

comment.html

{{define "tags"}}
<div>
    {{.Note}}
</div>
{{end}}

gocode

type Tags struct {
   Id int
   Name string
}

type Content struct {
   Id int
   Title string
   Content string
}

type Comment struct {
   Id int
   Note string
}


func main() {
    tags := &Tags{"Id":1, "Name":"golang"}
    Content := &Content{"Id":9, "Title":"Hello", "Content":"World!"}
    Comment := &Comment{"Id":2, "Note":"Good Day!"}
}

我很困惑,如何渲染每个子模板并将结果与​​布局输出结合起来。

谢谢。

go
1个回答
24
投票

一如既往,the doc是一个很好的起点。

I wrote a working example on the playground

解释一下:

  1. 结构文字中不需要字符串:&Tags{Id: 1},而不是&Tags{"Id":1}
  2. 您只能将单个对象传递给模板才能执行,这将根据您的需要在{{template <name> <arg>}}指令中将对象分派给每个子模板。我使用了一个特殊的Page结构,但如果你愿意,可以使用map[string]interface{}
  3. 你需要解析每个模板(我在Playground中使用了字符串,但是如果你已经有了你的html文件,ParseFiles会这样做)
  4. 我使用os.Stdout来执行它,但显然你应该用相应的ResponseWriter替换它

整个代码:

package main

import "fmt"
import "html/template"
import "os"

var page = `<html>
  <body>
    {{template "tags" .Tags}}

    {{template "content" .Content}}

    {{template "comment" .Comment}}
  </body>
</html>`

var tags = `{{define "tags"}}
<div>
    {{.Name}}
<div>
{{end}}`

var content = `{{define "content"}}
<div>
   <p>{{.Title}}</p>
   <p>{{.Content}}</p>
</div>
{{end}}`

var comment = `{{define "comment"}}
<div>
    {{.Note}}
</div>
{{end}}`

type Tags struct {
   Id int
   Name string
}

type Content struct {
   Id int
   Title string
   Content string
}

type Comment struct {
   Id int
   Note string
}

type Page struct {
    Tags *Tags
    Content *Content
    Comment *Comment
}

func main() {
    pagedata := &Page{Tags:&Tags{Id:1, Name:"golang"},
                      Content: &Content{Id:9, Title:"Hello", Content:"World!"},
                      Comment: &Comment{Id:2, Note:"Good Day!"}}
    tmpl := template.New("page")
    var err error
    if tmpl, err = tmpl.Parse(page); err != nil {
        fmt.Println(err)
    }
    if tmpl, err = tmpl.Parse(tags); err != nil {
        fmt.Println(err)
    }
    if tmpl, err = tmpl.Parse(comment); err != nil {
        fmt.Println(err)
    }
    if tmpl, err = tmpl.Parse(content); err != nil {
        fmt.Println(err)
    }
    tmpl.Execute(os.Stdout, pagedata)
}
© www.soinside.com 2019 - 2024. All rights reserved.