加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang模板 – 如何渲染模板?

发布时间:2020-12-16 19:29:09 所属栏目:大数据 来源:网络整理
导读:一个布局模板,带有三个子模板. 的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{{.Con
一个布局模板,带有三个子模板.

的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!"}
}

我很困惑,如何渲染每个子模板并将结果组合到布局输出.

谢谢.

和往常一样,the doc是一个很好的起点.

I wrote a working example on the playground

解释一下:

>你不需要在结构文字中使用字符串:&标签{Id:1},而不是&标签{“Id”:1}
>您只能将单个对象传递给您的模板来执行,这将按照{{template< name> < arg>}}指令.我使用了一个ad-hoc页面结构,但是如果你喜欢,map [string] interface {}将会做.
>你需要解析每个模板(我在游乐场中使用了字符串,但是如果你的html文件已经有ParseFiles的话)
>我使用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)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读