aboutsummaryrefslogtreecommitdiff
path: root/template.go
blob: a4c3ee0377bcc1c1a5102745e050caedfac99550 (plain) (blame)
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
50
51
52
53
54
55
56
package koushin

import (
	"fmt"
	"html/template"
	"io"
	"net/url"

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

type tmpl struct {
	// TODO: add support for multiple themes
	t *template.Template
}

func (t *tmpl) Render(w io.Writer, name string, data interface{}, ectx echo.Context) error {
	// ectx is the raw *echo.context, not our own *context
	ctx := ectx.Get("context").(*context)

	for _, plugin := range ctx.server.plugins {
		if err := plugin.Render(name, data); err != nil {
			return fmt.Errorf("failed to run plugin '%v': %v", plugin.Name(), err)
		}
	}

	return t.t.ExecuteTemplate(w, name, data)
}

func loadTemplates(logger echo.Logger, themeName string) (*tmpl, error) {
	base, err := template.New("").Funcs(template.FuncMap{
		"tuple": func(values ...interface{}) []interface{} {
			return values
		},
		"pathescape": func(s string) string {
			return url.PathEscape(s)
		},
	}).ParseGlob("public/*.html")
	if err != nil {
		return nil, err
	}

	theme, err := base.Clone()
	if err != nil {
		return nil, err
	}

	if themeName != "" {
		logger.Printf("Loading theme \"%s\"", themeName)
		if _, err := theme.ParseGlob("public/themes/" + themeName + "/*.html"); err != nil {
			return nil, err
		}
	}

	return &tmpl{theme}, err
}