现在我正在使用大猩猩语境包在我的中间件和控制器中传递数据,但是我想要做的是直接将数据传递给我的Pongo2模板,所以在控制器的后面,我不需要从Gorilla上下文中获取数据并手动地将它传递到模板上下文中,因为熟悉express.js的人就像
var user = {
name: "Name",
age: 0
}
response.locals = user编辑:所以每个pongo2模板都需要访问一个用户对象,现在我使用中间件从数据库中获取用户,并使用Gorilla上下文将数据传递给我的控制器,从那里传递给每个控制器上的模板,但是我想做的是从中间件中将用户对象传递给模板,而不是使用Gorilla上下文。
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)
})
}然后在我的请求中,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))
}对于我的所有处理程序,我必须向用户传递这样的模板,但是我想从中间件中传递它,这样我就不必在我的每个处理程序中执行它。
发布于 2015-09-10 07:07:22
调用MyExecute(req, tpl)而不是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))
}如果没有测试,它应该能工作。最大的问题是大猩猩使用map[interface{}]interface{}作为存储,而pongo使用map[string]interface{},注意不要在大猩猩上下文中使用非字符串作为键。
https://stackoverflow.com/questions/32493677
复制相似问题