I have struct that has JSON field something like this:
detail := &Detail{ Name string Detail json.RawMessage }
template looks like this:
detail = At {{Name}} {{CreatedAt}} {{UpdatedAt}}
My question can we use one or more structs for a single template or it is restricted to only one struct.
You can pass as many things as you like. You haven't provided much of an example to work with, so I'm going to assume a few things, but here's how you would tackle it:
// Shorthand - useful!
type M map[string]interface
func SomeHandler(w http.ResponseWriter, r *http.Request) {
detail := Detail{}
// From a DB, or API response, etc.
populateDetail(&detail)
user := User{}
populateUser(&user)
// Get a session, set headers, etc.
// Assuming tmpl is already a defined *template.Template
tmpl.RenderTemplate(w, "index.tmpl", M{
// We can pass as many things as we like
"detail": detail,
"profile": user,
"status": "", // Just an example
}
}
... and our template:
<!DOCTYPE html>
<html>
<body>
// Using "with"
{{ with .detail }}
{{ .Name }}
{{ .CreatedAt }}
{{ .UpdatedAt }}
{{ end }}
// ... or the fully-qualified way
// User has fields "Name", "Email", "Address". We'll use just two.
Hi there, {{ .profile.Name }}!
Logged in as {{ .profile.Email }}
</body>
</html>
Hope that clarifies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With