alps/template.go

62 lines
1.3 KiB
Go
Raw Normal View History

2019-12-02 14:31:00 +00:00
package koushin
import (
2019-12-09 15:02:12 +00:00
"fmt"
2019-12-02 14:31:00 +00:00
"html/template"
"io"
"net/url"
2019-12-02 14:31:00 +00:00
"github.com/labstack/echo/v4"
)
type tmpl struct {
// TODO: add support for multiple themes
2019-12-02 14:31:00 +00:00
t *template.Template
}
2019-12-09 15:02:12 +00:00
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.Inject(name, data); err != nil {
2019-12-09 15:02:12 +00:00
return fmt.Errorf("failed to run plugin '%v': %v", plugin.Name(), err)
}
}
2019-12-02 14:31:00 +00:00
return t.t.ExecuteTemplate(w, name, data)
}
2019-12-09 16:54:24 +00:00
func loadTemplates(logger echo.Logger, themeName string, plugins []Plugin) (*tmpl, error) {
base := template.New("").Funcs(template.FuncMap{
2019-12-03 12:07:25 +00:00
"tuple": func(values ...interface{}) []interface{} {
return values
},
"pathescape": func(s string) string {
return url.PathEscape(s)
},
2019-12-09 16:54:24 +00:00
})
for _, p := range plugins {
base = base.Funcs(p.Filters())
}
base, err := base.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
2019-12-02 14:31:00 +00:00
}