Oliver.Oakley
Oliver.Oakley

Reputation: 668

golang template with multiple structs

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.

Upvotes: 3

Views: 4097

Answers (1)

elithrar
elithrar

Reputation: 24250

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.

Upvotes: 6

Related Questions