Global template data

Brian Voelker picture Brian Voelker · Sep 18, 2012 · Viewed 8k times · Source

When doing ExecuteTemplate I see all examples using &whateversruct{Title: "title info", Body: "body info"} to send data to the template to replace the info. I was wondering if its possible to not have to create a struct outside my handler function because every handler function I have is not going to have the same Title, Body. It would be nice to be able to send it a map that replaces the template info. Any thoughts or ideas?

Currently - loosely written

type Info struct {
    Title string
    Body string
}

func View(w http.ResponseWriter) {
    temp.ExecuteTemplate(w, temp.Name(), &Info{Title: "title", Body: "body"})
}

Just seems like creating the struct is unnecessary. And the struct would not be the same for each function you create. So you would have to create a struct for each function (that I know of).

Answer

jimt picture jimt · Sep 19, 2012

To augment Kevin's answer: An anonymous struct will yield much the same behaviour:

func View(w http.ResponseWriter) {
    data := struct {
        Title string
        Body  string
    } {
        "About page",
        "Body info",
    }

    temp.ExecuteTemplate(w, temp.Name(), &data)
}