如何在Go语言的模板中多次使用解析(parse)函数?

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

How to use parse many times in golang's template

问题

我需要帮助。现在我使用多个模板来输出页面(例如1),我想在一个模板中多次使用解析(例如2)。

示例1:

  1. ...
  2. t, err := template.ParseFiles("header.html")
  3. t.Execute(wr, data)
  4. d, err := template.ParseFiles("content.html")
  5. d.Execute(wr, datatwo)
  6. ...

示例2:

  1. ...
  2. t := template.New("blabla")
  3. t.ParseFiles("header.html")
  4. t.ParseFiles("content.html")
  5. t.Execute("wr", data)

P.S. 很抱歉,我的英语很糟糕。

英文:

i need help. Now to output pages I use multiple templates(1 example) and i want to use parse many times in one template(2 example)

Example 1:

  1. ...
  2. t, err := template.ParseFiles("header.html")
  3. t.Execute(wr, data)
  4. d, err := template.ParseFiles("content.html")
  5. d.Execute(wr, datatwo)
  6. ...

Example 2:

  1. ...
  2. t := template.New("blabla")
  3. t.ParseFiles("header.html")
  4. t.ParseFiles("content.html")
  5. t.Execute("wr", data)

P.S. I'm sorry, my english is very bad

答案1

得分: 1

template.ParseFiles可以接受多个文件名作为参数,参考链接:http://golang.org/pkg/html/template/#ParseFiles

例如:

  1. t := template.New("base")
  2. t, err := t.ParseFiles("header.html", "footer.html", "content.html")
  3. if err != nil {
  4. // 处理错误
  5. }

在Go文档中也有一个关于如何使用html/template的实例:http://golang.org/doc/articles/wiki/#tmp_6

英文:

template.ParseFiles can take multiple filenames as an argument, as per http://golang.org/pkg/html/template/#ParseFiles

> func ParseFiles(filenames ...string) (*Template, error)

e.g.

  1. t := template.New("base")
  2. t, err := t.ParseFiles("header.html", "footer.html", "content.html")
  3. if err != nil {
  4. // handle the error
  5. }

There's a solid example on how to use html/template in the Go docs as well: http://golang.org/doc/articles/wiki/#tmp_6

huangapple
  • 本文由 发表于 2015年3月14日 13:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/29045823.html
匿名

发表评论

匿名网友

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

确定