From 6f31f35c7b38fbf63d7a0c9322458e0b75828495 Mon Sep 17 00:00:00 2001 From: Alexander Kiryukhin Date: Thu, 18 Mar 2021 02:06:42 +0300 Subject: Initial --- internal/renderer/renderer.go | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 internal/renderer/renderer.go (limited to 'internal/renderer') diff --git a/internal/renderer/renderer.go b/internal/renderer/renderer.go new file mode 100644 index 0000000..bed603c --- /dev/null +++ b/internal/renderer/renderer.go @@ -0,0 +1,45 @@ +package renderer + +import ( + "html/template" + "net/http" + "path" + "path/filepath" +) + +// Renderer represents html template renderer +type Renderer struct { + templates map[string]*template.Template +} + +// New Renderer +func New(gpath string) (*Renderer, error) { + t := &Renderer{ + templates: make(map[string]*template.Template), + } + + includes, err := filepath.Glob(path.Join(gpath, "includes/*.gohtml")) + if err != nil { + return nil, err + } + + pages, err := filepath.Glob(path.Join(gpath, "pages/*.gohtml")) + if err != nil { + return nil, err + } + + for _, p := range pages { + tpls := append(includes, p) + tname := path.Base(p) + t.templates[tname] = template.Must(template.New(tname).ParseFiles(tpls...)) + } + + return t, nil +} + +func (r *Renderer) Render(tpl string, data Map, rw http.ResponseWriter) error { + rw.Header().Set("Content-Type", "text/html") + return r.templates[tpl].Execute(rw, data) +} + +type Map map[string]interface{} -- cgit v1.2.3