zolamk
zolamk

Reputation: 6417

How to pass data to template automatically in Go?

Right now i am using Gorilla context package to pass data around in my middlewares & controllers, but what i want to do is pass the data directly to my Pongo2 template so later in my controller i don't have to get the data from the Gorilla context and manually pass it to the template context, for those of you familiar with express.js it would be like

var user = {
    name: "Name",
    age: 0
}

response.locals = user

Edit: So every pongo2 template needs access to a User object, right now i fetch the user from database using middleware and using Gorilla context pass the data to my controller, from there on to my template on each controller but what i want to do is pass the User object to template from my middleware instead of using Gorilla context.

func UserMiddleware(next http.HandlerFunc) http.HandlerFunc {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {

       user := &User{} // user will normally be fetched from database
       context.Set(req, "user", user)
       next.ServeHTTP(res, req)
    })
}

Then In My Request Handler

func Handler(res http.ResponseWriter, req *http.Request) {
    tpl, _ := pongo2.FromFile("view/template.html")
    user := context.Get(req, "user").(*User)
    data := pongo2.Context{
       "user": user,
    }
    out, _ := tpl.Execute(data)
    res.Write([]byte(out))
}

For all of my handlers i have to pass in user to template like that, but i want to pass it in from my middleware so that i don't have to do it in each of my handlers.

Upvotes: 0

Views: 1126

Answers (1)

Jiang YD
Jiang YD

Reputation: 3311

invoke MyExecute(req, tpl) instead of tpl.Execute(data)

func MyExecute(req *http.Request, tpl TemplateSet) (string, error){
    gorillaObj := context.GetAll(req)
    pongoObj := make(map[string]interface{})

    for key, value := range gorillaObj {
        if str, ok := key.(string); ok{
            pongoObj[str] = value
        }
    }

    return tpl.Execute(pongo2.Context(pongoObj))
}

not tested, it should work. the most problem is that gorilla use map[interface{}]interface{} as store, but pongo use map[string]interface{}, note not to use non-string as key in gorilla context.

Upvotes: 1

Related Questions