1
0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-12-04 19:08:22 +01:00

Add path functions for use in templates

This commit is contained in:
adnano 2021-05-10 11:12:26 -04:00
parent 66ac6015c9
commit 69f39d7303

@ -4,6 +4,7 @@ import (
"fmt"
htemplate "html/template"
"os"
"path"
"strings"
"text/template"
@ -62,32 +63,45 @@ func LoadConfig(path string) (*Config, error) {
URLs []string
}
funcs["site"] = func() Site {
return Site{
Title: c.Title,
URLs: c.URLs,
}
}
funcs["partial"] = func(name string, data interface{}) (interface{}, error) {
t, ok := c.templates.FindPartial(name)
if !ok {
return "", fmt.Errorf("Error: partial %q not found", name)
}
var b strings.Builder
if err := t.Execute(&b, data); err != nil {
return "", err
}
return b.String(), nil
}
// Initialize templates
c.templates = NewTemplates()
c.templates.Funcs(map[string]interface{}{
"site": func() Site {
return Site{
Title: c.Title,
URLs: c.URLs,
}
},
"partial": func(name string, data interface{}) (interface{}, error) {
t, ok := c.templates.FindPartial(name)
if !ok {
return "", fmt.Errorf("Error: partial %q not found", name)
}
var b strings.Builder
if err := t.Execute(&b, data); err != nil {
return "", err
}
return b.String(), nil
},
"safeHTML": func(s string) htemplate.HTML { return htemplate.HTML(s) },
"safeHTMLAttr": func(s string) htemplate.HTMLAttr { return htemplate.HTMLAttr(s) },
"safeCSS": func(s string) htemplate.CSS { return htemplate.CSS(s) },
"safeJS": func(s string) htemplate.JS { return htemplate.JS(s) },
"safeURL": func(s string) htemplate.URL { return htemplate.URL(s) },
})
c.templates.Funcs(funcs)
return c, nil
}
var funcs = map[string]interface{}{
"safeHTML": func(s string) htemplate.HTML { return htemplate.HTML(s) },
"safeHTMLAttr": func(s string) htemplate.HTMLAttr { return htemplate.HTMLAttr(s) },
"safeCSS": func(s string) htemplate.CSS { return htemplate.CSS(s) },
"safeJS": func(s string) htemplate.JS { return htemplate.JS(s) },
"safeURL": func(s string) htemplate.URL { return htemplate.URL(s) },
"path": func() map[string]interface{} { return pathFuncs },
}
var pathFuncs = map[string]interface{}{
"Base": path.Base,
"Clean": path.Clean,
"Dir": path.Dir,
"Ext": path.Ext,
"Join": path.Join,
"Split": path.Split,
}