From dc33adb733ace846da99eedee23d78c724a81211 Mon Sep 17 00:00:00 2001 From: "Gustavo \"Guz\" L de Mello" Date: Thu, 6 Mar 2025 16:55:16 -0300 Subject: [PATCH] feat: args func to pass multiple arguments to templates --- templates/templates.go | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/templates/templates.go b/templates/templates.go index 7bb6723..d87cfbb 100644 --- a/templates/templates.go +++ b/templates/templates.go @@ -2,15 +2,36 @@ package templates import ( "embed" + "errors" + "fmt" "html/template" ) -//go:embed *.html test/*.html +//go:embed *.html layouts/*.html var embedded embed.FS -var temps = template.Must(template.ParseFS(embedded, +var temps = template.Must(template.New("templates").Funcs(template.FuncMap{ + "args": func(pairs ...any) (map[string]any, error) { + if len(pairs)%2 != 0 { + return nil, errors.New("misaligned map in template arguments") + } + + m := make(map[string]any, len(pairs)/2) + + for i := 0; i < len(pairs); i += 2 { + key, ok := pairs[i].(string) + if !ok { + return nil, fmt.Errorf("cannot use type %T as map key", pairs[i]) + } + + m[key] = pairs[i+1] + } + + return m, nil + }, +}).ParseFS(embedded, "*.html", - "test/*.html", + "layouts/*.html", )) func Templates() *template.Template {