Templates 使用Golang模板,如何在每个模板中设置变量?
如何在每个模板中设置可以在其他模板中使用的变量,例如Templates 使用Golang模板,如何在每个模板中设置变量?,templates,go,Templates,Go,如何在每个模板中设置可以在其他模板中使用的变量,例如 {{set title“title}} 在一个模板中,然后在我的布局中 {{title}} 然后当它被渲染时 tmpl,\:=template.ParseFiles(“layout.html”、“home.html”) 它将根据在home.html中设置的内容设置标题,而不必在没有必要时为每个查看页面创建struct。我希望我讲得通,谢谢 请澄清: layout.html: <!DOCTYPE html> <html>
{{set 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>
layout.html:
{{title}}
home.html:
{{设置标题“主页”。}
{{Title}}页
如果要在另一个模板中使用该值,可以通过管道将其传输到dot:
{{with $title := "SomeTitle"}}
{{$title}} <--prints the value on the page
{{template "body" .}}
{{end}}
layout.html
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}} </title>
</head>
<body>
{{template "body" .}}
</body>
</html>
{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}
{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}
{{.Title}
{{模板“主体”}
home.html
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}} </title>
</head>
<body>
{{template "body" .}}
</body>
</html>
{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}
{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}
{{define“body”}
home.html{{.Title}
{{end}
page.html
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}} </title>
</head>
<body>
{{template "body" .}}
</body>
</html>
{{define "body"}}
<h1>home.html {{.Title}}</h1>
{{end}}
{{define "body"}}
<h1>page.html {{.Title}}</h1>
{{end}}
{{define“body”}
page.html{{.Title}
{{end}
go还有一个关于如何使用模板的很好的文档: