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.
{{ template "header" . }}
(note the.
) – Anaclinal