我试图使用 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 as 类型上使用 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.
在这种情况下,您传入的管道是.
,它引用了整个数据
。
html/template
的文档大多在text/template
中,有点不方便。
关于http - 将数据传递给嵌套模板未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612442/