将数据传递到嵌套模板不能按预期方式工作

I was trying to get a struct passed to a nested template in Go, using html/template and tried to achieve it using both template.ParseFiles and template.ParseGlob, but it is not working as per my expectation because my understanding is not clear.

My template code for the file header.html is

{{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}} 

and for the file admin.html is

{{template "header"}}
<body>
"User is {{.User}}"
</body>
</html>

I am using the Execute method on the type *Template as

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)

With the above code, I can pass around the struct data to admin.html, and it shows User is Guest in the browser. But if I try to pass it to any of the nested templates, it wouldn't. The title of the page still shows as SiteAdmin - and not SiteAdmin - Guest. The User data from the struct is visible only if I call it as {{.User}} inside the admin.html file, and any reference to it in the nested templates turns out to be not passed. Is this something achievable?

Thank you all.

dqdes60666
dqdes60666 哇,谢谢@leafbebop,它起作用了。您可以将其发布为答案吗?我会接受的。另外,文档中是否有提及?我想知道我应该在哪里寻找它。
2 年多之前 回复
dongpi9164
dongpi9164 可能您需要使用{{template“header”。}}(请注意。)
2 年多之前 回复

1个回答



您需要使用 {{模板“ header”。 }} </代码>。 正如 文本/模板</ code> 中的文档所说 :</ p>


{{模板“名称”管道}}} </ p>

指定名称的模板使用点集执行
</ p>
</ blockquote>

在这种情况下,您传入的管道是。</ code>,它代表整个数据</ code>。</ p>

html / template </ code>的文档大多位于 text / template </ code>中,这有点不便。 / p>
</ div>

展开原文

原文

You need to use {{ template "header" . }}. As the document in text/template say:

{{template "name" pipeline}}

The template with the specified name is executed with dot set to the value of the pipeline.

In this case, the pipeline you passed into is ., which reffers to the whole data.

It is somehow unconvenient that documents of html/template is mostly in text/template.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐