如何在每个模板中设置可以在其他模板中使用的变量,例如
{{ 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>
如果要在另一个模板中使用“值”,则可以将其通过管道传递到点:
{{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
,因此您不能将值传递回去。
在您的例子这将是使用结构,并通过它从最好的解决方案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)
}
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}}
还可以找到有关如何使用模板的不错的文档:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句