From 5b5ad6ee2f632d1ddc54490ab53f89fb4705d3ae Mon Sep 17 00:00:00 2001 From: raul Date: Wed, 22 May 2024 12:40:44 +0200 Subject: [PATCH] Add helper file for embedding templates to Gin --- cmd/embedTemplates.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 cmd/embedTemplates.go diff --git a/cmd/embedTemplates.go b/cmd/embedTemplates.go new file mode 100644 index 0000000..7718f53 --- /dev/null +++ b/cmd/embedTemplates.go @@ -0,0 +1,39 @@ +package cmd + +import ( + "embed" + "github.com/gin-gonic/gin" + "html/template" + "io/fs" + "regexp" + "strings" +) + +func LoadHTMLFromEmbedFS(engine *gin.Engine, embedFS embed.FS, pattern string) { + root := template.New("") + tmpl := template.Must(root, LoadAndAddToRoot(engine.FuncMap, root, embedFS, pattern)) + engine.SetHTMLTemplate(tmpl) +} +func LoadAndAddToRoot(funcMap template.FuncMap, rootTemplate *template.Template, embedFS embed.FS, pattern string) error { + pattern = strings.ReplaceAll(pattern, ".", "\\.") + pattern = strings.ReplaceAll(pattern, "*", ".*") + + err := fs.WalkDir(embedFS, ".", func(path string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + + if matched, _ := regexp.MatchString(pattern, path); !d.IsDir() && matched { + data, readErr := embedFS.ReadFile(path) + if readErr != nil { + return readErr + } + t := rootTemplate.New(path).Funcs(funcMap) + if _, parseErr := t.Parse(string(data)); parseErr != nil { + return parseErr + } + } + return nil + }) + return err +}