20

例如.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": "My title", "Body": "Hi this is my body"})
}

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

在 header.html 中:

Title is {{.Title}}

在页脚.html 中:

Body is {{.Body}}

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

提前致谢。

4

2 回答 2

29

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

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

"footer.html"将数据从Executethrough 传递到页脚模板后的点- 传递的值成为.包含的模板。

于 2012-09-01T15:41:42.117 回答
22

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

这里有一点改进。

header.html:

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

页脚.html:

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

这样footer.html就可以改成任何定义“footer”的文件,制作不同的页面

于 2012-12-04T07:13:20.807 回答