From 29795fa5b18cafcec369542b75909be286f60ed7 Mon Sep 17 00:00:00 2001 From: Adnan Maolood Date: Mon, 10 May 2021 11:12:26 -0400 Subject: [PATCH] Add path functions for use in templates --- config.go | 62 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/config.go b/config.go index b9607b6..b9b9d9d 100644 --- a/config.go +++ b/config.go @@ -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, +}