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

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

How to use parse many times in golang's template

问题

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

示例1:

...
t, err := template.ParseFiles("header.html")
t.Execute(wr, data)
d, err := template.ParseFiles("content.html")
d.Execute(wr, datatwo)
...

示例2:

...
t := template.New("blabla")
t.ParseFiles("header.html")
t.ParseFiles("content.html")
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:

...
t, err := template.ParseFiles("header.html")
t.Execute(wr, data)
d, err := template.ParseFiles("content.html")
d.Execute(wr, datatwo)
...

Example 2:

...
t := template.New("blabla")
t.ParseFiles("header.html")
t.ParseFiles("content.html")
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

例如:

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

在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.

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

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:

确定