如果您想在另一个模板中使用该值,您可以将其通过管道传递到点:
{{with $title := "SomeTitle"}}
{{$title}} <--prints the value on the page
{{template "body" .}}
{{end}}
正文模板:
{{define "body"}}
<h1>{{.}}</h1> <--prints "SomeTitle" again
{{end}}
据我所知,不可能在链条中向上走。
所以layout.html 在home.html 之前被渲染,所以你不能传回一个值。
在您的示例中,最好的解决方案是使用结构并使用dot 将其从layout.html 传递到home.html:
main.go
package main
import (
"html/template"
"net/http"
)
type WebData struct {
Title string
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("layout.html", "home.html")
wd := WebData{
Title: "Home",
}
tmpl.Execute(w, &wd)
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("layout.html", "page.html")
wd := WebData{
Title: "Page",
}
tmpl.Execute(w, &wd)
}
func main() {
http.HandleFunc("/home", homeHandler)
http.HandleFunc("/page", pageHandler)
http.ListenAndServe(":8080", nil)
}
layout.html
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}} </title>
</head>
<body>
{{template "body" .}}
</body>
</html>
home.html
{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}
page.html
{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}
还有一个很好的关于如何使用模板的文档:
http://golang.org/pkg/text/template/