Gin 如何让通过中间件设置的变量 在模板中能读取到

1. 运行环境

g o 1.18.1, darwin/amd64

2. 问题描述?

router := gin.Default()

router.use(func (ctx *gin.Context) {
    // if user.isLogged()
        // 怎么才能设置一个变量或值,让模板中可以读到
    // endif
})

如fiber可以这样:

app.Use(func(ctx *fiber.Ctx) error {
    _ = ctx.Bind(fiber.Map{
        "t": time.Now().UnixNano(),
    })
    return ctx.Next()
})

app.Get("/", func(ctx *fiber.Ctx) error {
    return ctx.Render("tmpl_name", fiber.Map{
    })
})

// 模板中可以  {{ .t }} 得到当前的时间戳
最佳答案

问题已解决。

不适用gin的模板逻辑即可。

1年前 评论
讨论数量: 6

想不出用go还写模版的必要,模版技术就只用php能用

c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "ctx": "这里不是任意参数吗? ",
        })
1年前 评论

如果非要,我的想法是可用将数据 Set 到 gin 的上下文 ctx 中 ctx.Set(),然后在 handler 中通过 ctx.Get() 拿到。

1年前 评论
cevin (楼主) 1年前

这就好像用汇编语言,写面向对象的高级功能一样!根本就没有必要,都是API,Gin,主要是也是面相API的

1年前 评论

问题已解决。

不适用gin的模板逻辑即可。

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!