如何在每个模板中设置一个可以在其他模板中使用的变量,例如
{{ set title "Title" }}
在一个模板中然后在我的布局中
<title> {{ title }} </title>
然后在渲染的时候
tmpl, _ := template.ParseFiles("layout.html", "home.html")
它将根据 home.html
中设置的内容设置标题而不是必须制作 struct
在没有必要时为每个 View 页面。我希望我说得有道理,谢谢。
只是为了澄清:
layout.html:
<!DOCTYPE html>
<html>
<head>
<title>{{ title }} </title>
</head>
<body>
</body>
</html>
home.html:
{{ set Title "Home" . }}
<h1> {{ Title }} Page </h1>
最佳答案
如果您想在另一个模板中使用该值,您可以将其通过管道传输到点:
{{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}}
还有一个关于如何使用模板的很好的文档:
关于templates - 使用 Golang 模板如何在每个模板中设置变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30609485/