dt250827 2015-09-10 05:16
浏览 29
已采纳

如何在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.

  • 写回答

1条回答 默认 最新

  • dotif64826 2015-09-10 07:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看