The current Render interface accepts only a http.ResponseWriter
:
type Render interface {
Render(http.ResponseWriter) error
}
I'm wondering if there's any reason the *http.Request
isn't accepted along with it.
The reason for considering this change is to be able to provide default values to the templates that require access to the users cookie.
Consider flash messages or information about logged in users... It's annoying to have to populate gin.H
with that information each time we call context.HTML
. If the Render
interface was updated to accept the *http.Request
, we could easily provide our own HTMLRender
to Engine
and have it perform this work automatically for us.
Comment From: ljluestc
type MyHTMLRender struct {
TemplateName string
}
func (r *MyHTMLRender) Render(w http.ResponseWriter, req *http.Request) error {
// Access request data like cookies or session data
userCookie, err := req.Cookie("user")
if err != nil {
userCookie = &http.Cookie{Name: "user", Value: "guest"}
}
// Define a context for template rendering
data := gin.H{
"user": userCookie.Value,
}
// Render the template with gin's context
tmpl := template.Must(template.New(r.TemplateName).ParseFiles(r.TemplateName))
return tmpl.Execute(w, data)
}