summaryrefslogblamecommitdiff
path: root/internal/renderer/renderer.go
blob: bed603c86acb8b586d73e9fbb351a17e90f1d37d (plain) (tree)












































                                                                                           
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{}