如何在每个模板中设置一个我可以在其他模板中使用的变量,例如
{{ set title "Title" }}
在一个模板然后在我的布局中
<title> {{ title }} </title>
然后当它被渲染
tmpl, _ := template.ParseFiles("layout.html", "home.html")
它将根据设置的内容设置标题,home.html
而不是在struct
没有必要时为每个视图页面设置.我希望我有道理,谢谢.
只是为了澄清:
layout.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }} </title>
</head>
<body>
</body>
</html>
home.html:
{{ set Title "Home" . }}
<h1> {{ Title }} Page </h1>
Run Code Online (Sandbox Code Playgroud)
如果要在另一个模板中使用Value,可以将其传递给点:
{{with $title := "SomeTitle"}}
{{$title}} <--prints the value on the page
{{template "body" .}}
{{end}}
Run Code Online (Sandbox Code Playgroud)
身体模板:
{{define "body"}}
<h1>{{.}}</h1> <--prints "SomeTitle" again
{{end}}
Run Code Online (Sandbox Code Playgroud)
据我所知,链条上不可能向上.所以layout.html
之前得到渲染home.html
,所以你不能传回一个值.
在您的例子这将是使用结构,并通过它从最好的解决方案layout.html
中,以home.html
使用dot
:
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)
}
Run Code Online (Sandbox Code Playgroud)
的layout.html
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}} </title>
</head>
<body>
{{template "body" .}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
home.html的
{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}
Run Code Online (Sandbox Code Playgroud)
page.html中
{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}
Run Code Online (Sandbox Code Playgroud)
还有一个关于如何使用模板的很好的文档:
http://golang.org/pkg/text/template/