Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global template data

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).

like image 744
Brian Voelker Avatar asked Nov 28 '22 05:11

Brian Voelker


1 Answers

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)
}
like image 76
jimt Avatar answered Feb 20 '23 20:02

jimt