aboutsummaryrefslogtreecommitdiffhomepage
path: root/backend/admin/renderer.go
blob: d38c701a390ecd76fb92faae7114d80cf07a69cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package admin

import (
	"embed"
	"html/template"
	"io"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

var (
	//go:embed templates
	templatesFS embed.FS
	//go:embed assets
	assetsFS embed.FS
)

type Renderer struct {
	templates map[string]*template.Template
}

func NewRenderer() *Renderer {
	return &Renderer{
		templates: make(map[string]*template.Template),
	}
}

func (r *Renderer) Render(w io.Writer, name string, data interface{}, _ echo.Context) error {
	tmpl, ok := r.templates[name]
	if !ok {
		t, err := template.ParseFS(templatesFS, "templates/base.html", "templates/"+name+".html")
		if err != nil {
			return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
		}
		r.templates[name] = t
		tmpl = t
	}
	return tmpl.ExecuteTemplate(w, name+".html", data)
}

func newAssetsMiddleware() echo.MiddlewareFunc {
	return middleware.StaticWithConfig(middleware.StaticConfig{
		Root:       "/assets",
		Filesystem: http.FS(assetsFS),
		IgnoreBase: true,
	})
}