router := gin.Default()
router.use(func (ctx *gin.Context) {
// if user.isLogged()
// how define a variable use in template
// endif
})
like fiber can do this
app.Use(func(ctx *fiber.Ctx) error {
_ = ctx.Bind(fiber.Map{
"time": time.Now().UnixNano(),
})
return ctx.Next()
})
app.Get("/", func(ctx *fiber.Ctx) error {
return ctx.Render("tmpl_name", fiber.Map{
})
})
// in template use {{ .time }}
Scenarios such as public page title suffix
{{ .page_title }} - {{ .common_title_suffix }}
page title - site-name
Comment From: toudi
how about c.Set
and c.Get
? so in your example:
router.use(func (ctx *gin.Context) {
// if user.isLogged()
c.Set("userName", "fooBar")
// endif
})
app.GET("/", func(c *gin.Context) {
user, exists := c.Get("userName")
if exists {
// user is an interface so you have to cast it to a propert (already known type) like so:
userName := user.(string)
// or a pointer like so:
// stuffFromContext := user.(*someModelStruct)
}
})
Comment From: cevin
how about
c.Set
andc.Get
? so in your example:```go router.use(func (ctx *gin.Context) { // if user.isLogged() c.Set("userName", "fooBar") // endif })
app.GET("/", func(c gin.Context) { user, exists := c.Get("userName") if exists { // user is an interface so you have to cast it to a propert (already known type) like so: userName := user.(string) // or a pointer like so: // stuffFromContext := user.(someModelStruct) } }) ```
However, for Fiber and Echo, it feels better to have Ctx's dedicated Map objects automatically merged into template variables when performing template rendering.
Otherwise in the case of Gin, when I have a lot of Handlers, I need to write gin.H{ xx: ctx.Get() }
repeatedly in each Handle. That's too bad.