noh*_*hup 5 parsing nested http go go-templates
我试图让传递到围棋嵌套模板结构,使用html/template和尝试了使用既达到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>
我在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)
使用上面的代码,我可以将结构体数据传递给admin.html,并显示User is Guest在浏览器中。但是,如果我尝试将其传递给任何嵌套模板,则不会。页面标题仍然显示为SiteAdmin -和SiteAdmin - Guest。User结构中的数据只有在我将其作为文件{{.User}}内部调用时才可见admin.html,并且嵌套模板中对它的任何引用都不会被传递。这是可以实现的吗?
谢谢你们。
您需要使用{{ template "header" . }}. 正如文件中text/template所说:
{{模板“名称”管道}}
执行具有指定名称的模板时将点设置为管道的值。
在这种情况下,您传入的管道是.,它涉及整个data.
文档html/template大多在text/template.
| 归档时间: | 
 | 
| 查看次数: | 1877 次 | 
| 最近记录: |