From 7b91ce35fd3574279eb268b76ce0f72510d45819 Mon Sep 17 00:00:00 2001 From: Mikhail Kirillov Date: Sat, 9 Jan 2021 18:54:32 +0300 Subject: [PATCH] issue #26 separated templates --- context.go | 9 +++++---- global.go | 4 ++++ router.go | 6 ++---- server.go | 6 ++++++ 4 files changed, 17 insertions(+), 8 deletions(-) diff --git a/context.go b/context.go index 7ebe264..e4924f3 100644 --- a/context.go +++ b/context.go @@ -20,6 +20,7 @@ type Context struct { qw Query statusCode int errorHandler ErrorHandler + tt *tt.TT } func (c *Context) StandardError(code int) { @@ -222,13 +223,13 @@ func (c *Context) SetCookie(cookie *http.Cookie) { func (c *Context) Render(tmpl string, vars map[string]interface{}) { - v := tt.MakeVars() + v := c.tt.MakeVars() for k, val := range vars { v.Set(k, val) } - if res, err := tt.Render(tmpl, v); err == nil { + if res, err := c.tt.Render(tmpl, v); err == nil { c.Write(res) } else { if c.errorHandler != nil { @@ -239,13 +240,13 @@ func (c *Context) Render(tmpl string, vars map[string]interface{}) { func (c *Context) RenderStr(tmpl string, vars map[string]interface{}) { - v := tt.MakeVars() + v := c.tt.MakeVars() for k, val := range vars { v.Set(k, val) } - if res, err := tt.RenderString(tmpl, v); err == nil { + if res, err := c.tt.RenderString(tmpl, v); err == nil { c.Write(res) } else { if c.errorHandler != nil { diff --git a/global.go b/global.go index a7b4b40..36c20cf 100644 --- a/global.go +++ b/global.go @@ -63,3 +63,7 @@ func RegMethod(method string, fn interface{}) { func RegisterJsonRPC(url string) { server.RegisterJsonRPC(url) } + +func LoadTemplates(dir string) { + server.LoadTemplates(dir) +} diff --git a/router.go b/router.go index fd713ab..40bf1e0 100644 --- a/router.go +++ b/router.go @@ -46,6 +46,7 @@ type router struct { staticHandlers map[string]http.Handler fileHandlers map[string]http.Handler authCheck AuthCheck + tt *tt.TT } func (sr *router) optionsOrNotFound(c *Context) { @@ -77,6 +78,7 @@ func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { req: req, params: make(map[string]string), errorHandler: r.errorHandler, + tt: r.tt, } defer func() { @@ -207,7 +209,3 @@ func makeUid(rw http.ResponseWriter, req *http.Request) { http.SetCookie(rw, cookie) } - -func LoadTemplates(dir string) { - tt.Open(dir) -} diff --git a/server.go b/server.go index 53b2b10..dff6f83 100644 --- a/server.go +++ b/server.go @@ -8,6 +8,7 @@ import ( "time" "github.com/wmentor/jrpc" + "github.com/wmentor/tt" ) type Server struct { @@ -29,6 +30,7 @@ func New() *Server { staticHandlers: make(map[string]http.Handler), fileHandlers: make(map[string]http.Handler), authCheck: func(login string, passwd string) bool { return false }, + tt: tt.New(), } s.jrpc = jrpc.New() @@ -183,3 +185,7 @@ func (s *Server) RegisterJsonRPC(url string) { }) } + +func (s *Server) LoadTemplates(dir string) { + s.router.tt = tt.New(dir) +}