3

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.

5
  • 1
    Detail is one struct, and it contains a Name string and json.RawMessage which is a bunch of bytes. Your template mentions CreatedAt and UpdatedAt. If your goal is to extract fields from the json.RawMessage and put them in the template, there are lots of ways to do that. Could you clarify your question? Commented Aug 15, 2014 at 17:19
  • yes I wanted to extract fields from json and add them in the same template. Also my question, is there a way we can work with multiple structs for one template? Commented Aug 15, 2014 at 17:44
  • AFAIK you can pass in only one "object" for your template, but that object could be, for instance, an array of structs of whatever type you want. HTH. Commented Aug 15, 2014 at 18:03
  • can you provide a valid playgroud snippet of what you want to do ? Commented Aug 15, 2014 at 18:34
  • I initially had multiple structs for a template, but I embedded these structs into a single struct this solved my problem Commented Aug 15, 2014 at 21:28

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.