在golang中使用template.ParseFiles解析多个文件

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

Multiple files using template.ParseFiles in golang

问题

例如.go,我有

package main

import "html/template"
import "net/http"

func handler(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("header.html", "footer.html")
	t.Execute(w, map[string]string{"Title": "我的标题", "Body": "嗨,这是我的正文"})
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

在header.html中:

标题是{{.Title}}

在footer.html中:

正文是{{.Body}}

当访问http://localhost:8080/时,我只看到"标题是我的标题",而不是第二个文件footer.html。如何使用template.ParseFiles加载多个文件?最有效的方法是什么?

提前致谢。

英文:

For example.go, I have

package main

import "html/template"
import "net/http"

func handler(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("header.html", "footer.html")
	t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

In header.html:

Title is {{.Title}}

In footer.html:

Body is {{.Body}}

When going to http://localhost:8080/, I only see "Title is My title", and not the second file, footer.html. How can I load multiple files with template.ParseFiles? What's the most efficient way to do this?

Thanks in advance.

答案1

得分: 31

只有第一个文件被用作主模板。其他模板文件需要从第一个文件中包含,如下所示:

标题是 {{.Title}}
{{template "footer.html" .}}

"footer.html"后面的点将数据从Execute传递到页脚模板 - 传递的值在包含的模板中变为.

英文:

Only the first file is used as the main template. The other template files need to be included from the first like so:

Title is {{.Title}}
{{template "footer.html" .}}

The dot after "footer.html" passes the data from Execute through to the footer template -- the value passed becomes . in the included template.

答案2

得分: 23

user634175的方法中有一个小缺点:第一个模板中的{{template "footer.html" .}}必须是硬编码的,这使得将footer.html更改为另一个页脚变得困难。

这里有一个小改进。

header.html:

标题是{{.Title}}
{{template "footer" .}}

footer.html:

{{define "footer"}}正文是{{.Body}}{{end}}

这样,footer.html可以更改为定义了"footer"的任何文件,以创建不同的页面。

英文:

There is a little shortcoming in user634175's method: the {{template "footer.html" .}} in the first template must be hard coded, which makes it difficult to change footer.html to another footer.

And here is a little improvement.

header.html:

Title is {{.Title}}
{{template "footer" .}}

footer.html:

{{define "footer"}}Body is {{.Body}}{{end}}

So that footer.html can be changed to any file that defines "footer", to make different pages

huangapple
  • 本文由 发表于 2012年9月1日 10:30:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/12224436.html
匿名

发表评论

匿名网友

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

确定