zdravko/web/templates/templates.go

99 lines
2.3 KiB
Go
Raw Permalink Normal View History

package templates
import (
"embed"
"io"
"io/fs"
"log/slog"
2024-02-22 19:20:34 +00:00
"strings"
"text/template"
2024-02-29 14:12:20 +00:00
"time"
"github.com/labstack/echo/v4"
"github.com/mentos1386/zdravko/pkg/script"
)
2024-02-11 10:56:21 +00:00
//go:embed *
var templates embed.FS
const base = "components/base.tmpl"
type Templates struct {
logger *slog.Logger
templates map[string]*template.Template
}
2024-06-07 09:43:32 +00:00
func load(version string, files ...string) *template.Template {
files = append(files, base)
2024-02-22 19:20:34 +00:00
t := template.New("default").Funcs(
template.FuncMap{
"MathDivide": func(a, b int) float64 {
if b == 0 {
return 0
}
return float64(a) / float64(b)
},
2024-05-25 17:52:37 +00:00
"DurationRoundSecond": func(d time.Duration) time.Duration {
return d.Round(time.Second)
},
"DurationRoundMillisecond": func(d time.Duration) time.Duration {
return d.Round(time.Millisecond)
},
"StringsJoin": strings.Join,
"Now": time.Now,
"ScriptUnescapeString": script.UnescapeString,
"ScriptEscapeString": script.EscapeString,
2024-06-07 09:43:32 +00:00
"Version": func() string {
return version
},
2024-02-22 19:20:34 +00:00
})
return template.Must(t.ParseFS(templates, files...))
}
2024-06-07 09:43:32 +00:00
func loadSettings(version string, files ...string) *template.Template {
files = append(files, "components/settings.tmpl")
2024-06-07 09:43:32 +00:00
return load(version, files...)
}
2024-06-07 09:43:32 +00:00
func NewTemplates(version string, logger *slog.Logger) (*Templates, error) {
t := Templates{
logger: logger,
templates: map[string]*template.Template{},
}
err := fs.WalkDir(templates, "pages", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if strings.Contains(path, ".tmpl") {
t.logger.Debug("Loading template", "path", path)
pathWithoutPrefix := strings.TrimPrefix(path, "pages/")
if strings.Contains(path, "settings") {
2024-06-07 09:43:32 +00:00
t.templates[pathWithoutPrefix] = loadSettings(version, path)
} else {
2024-06-07 09:43:32 +00:00
t.templates[pathWithoutPrefix] = load(version, path)
}
}
return nil
})
return &t, err
}
func (t *Templates) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
if t.templates[name] == nil {
t.logger.Error("template not found", "template", name)
return echo.ErrNotFound
}
err := t.templates[name].ExecuteTemplate(w, "base", data)
if err != nil {
t.logger.Error("error rendering template", "template", err)
}
return err
}