将数据传递给嵌套模板未按预期工作
Passing data to a nested template not working as expected
我试图使用 html/template
将结构传递给 Go 中的嵌套模板,并尝试使用 template.ParseFiles
和 template.ParseGlob
来实现它,但它不起作用符合我的预期,因为我的理解不明确。
我的文件 header.html
模板代码是
{{define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> SiteAdmin - {{.User}}</title>
</head>
{{end}}
文件 admin.html
是
{{template "header"}}
<body>
"User is {{.User}}"
</body>
</html>
我在类型 *Template 上使用 Execute
方法作为
type Admin struct {
User string
}
data := new(Admin)
data.User = "Guest"
tpl, err := template.ParseGlob("views/templates/admin/*.html")
CheckForErr(err)
err = tpl.Execute(w, data)
CheckForErr(err)
使用上面的代码,我可以将结构数据传递给 admin.html
,它在浏览器中显示 User is Guest
。但是,如果我尝试将它传递给任何嵌套模板,它就不会。页面标题仍显示为 SiteAdmin -
而不是 SiteAdmin - Guest
。只有当我在 admin.html
文件中将它称为 {{.User}}
时,结构中的 User
数据才可见,并且在嵌套模板中对它的任何引用都不会被传递。这是可以实现的吗?
谢谢大家
您需要使用 {{ template "header" . }}
。正如 text/template
中的文档所说:
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.
在这种情况下,您传入的管道是.
,它指的是整个data
。
html/template
的文档大多在text/template
.
,有点不方便
我试图使用 html/template
将结构传递给 Go 中的嵌套模板,并尝试使用 template.ParseFiles
和 template.ParseGlob
来实现它,但它不起作用符合我的预期,因为我的理解不明确。
我的文件 header.html
模板代码是
{{define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> SiteAdmin - {{.User}}</title>
</head>
{{end}}
文件 admin.html
是
{{template "header"}}
<body>
"User is {{.User}}"
</body>
</html>
我在类型 *Template 上使用 Execute
方法作为
type Admin struct {
User string
}
data := new(Admin)
data.User = "Guest"
tpl, err := template.ParseGlob("views/templates/admin/*.html")
CheckForErr(err)
err = tpl.Execute(w, data)
CheckForErr(err)
使用上面的代码,我可以将结构数据传递给 admin.html
,它在浏览器中显示 User is Guest
。但是,如果我尝试将它传递给任何嵌套模板,它就不会。页面标题仍显示为 SiteAdmin -
而不是 SiteAdmin - Guest
。只有当我在 admin.html
文件中将它称为 {{.User}}
时,结构中的 User
数据才可见,并且在嵌套模板中对它的任何引用都不会被传递。这是可以实现的吗?
谢谢大家
您需要使用 {{ template "header" . }}
。正如 text/template
中的文档所说:
{{template "name" pipeline}}
The template with the specified name is executed with dot set to the value of the pipeline.
在这种情况下,您传入的管道是.
,它指的是整个data
。
html/template
的文档大多在text/template
.