将数据传递给嵌套模板未按预期工作

noh*_*hup 5 parsing nested http go go-templates

我试图让传递到围棋嵌套模板结构,使用html/template和尝试了使用既达到template.ParseFilestemplate.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}} 
Run Code Online (Sandbox Code Playgroud)

对于文件admin.html

{{template "header"}}
<body>
"User is {{.User}}"
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我在Execute*Template 类型上使用该方法作为

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)
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,我可以将结构体数据传递给admin.html,并显示User is Guest在浏览器中。但是,如果我尝试将其传递给任何嵌套模板,则不会。页面标题仍然显示为SiteAdmin -SiteAdmin - GuestUser结构中的数据只有在我将其作为文件{{.User}}内部调用时才可见admin.html,并且嵌套模板中对它的任何引用都不会被传递。这是可以实现的吗?

谢谢你们。

lea*_*bop 8

您需要使用{{ template "header" . }}. 正如文件中text/template所说:

{{模板“名称”管道}}

执行具有指定名称的模板时将点设置为管道的值。

在这种情况下,您传入的管道是.,它涉及整个data.

文档html/template大多在text/template.