fix: embed templates directly
All checks were successful
ci/woodpecker/tag/release Pipeline was successful

This commit is contained in:
Felipe M 2025-04-21 15:10:08 +02:00
parent 3426b668fe
commit bbb48f49e2
Signed by: fmartingr
GPG key ID: CCFBC5637D4000A8

View file

@ -1,9 +1,9 @@
package admin package admin
import ( import (
"embed"
"html/template" "html/template"
"net/http" "net/http"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
@ -14,12 +14,12 @@ import (
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
) )
//go:embed templates/*.html
var templateFS embed.FS
const ( const (
// Session store key // Session store key
sessionKey = "butterrobot-session" sessionKey = "butterrobot-session"
// Template directory
templateDir = "./internal/admin/templates"
) )
// FlashMessage represents a flash message // FlashMessage represents a flash message
@ -63,9 +63,17 @@ func New(cfg *config.Config, database *db.Database) *Admin {
"contains": strings.Contains, "contains": strings.Contains,
} }
// Read base template from embedded filesystem
baseContent, err := templateFS.ReadFile("templates/_base.html")
if err != nil {
panic(err)
}
// Create a custom template with functions // Create a custom template with functions
baseTemplate := template.New("_base.html").Funcs(funcMap) baseTemplate, err := template.New("_base.html").Funcs(funcMap).Parse(string(baseContent))
baseTemplate = template.Must(baseTemplate.ParseFiles(filepath.Join(templateDir, "_base.html"))) if err != nil {
panic(err)
}
// Parse and register all templates // Parse and register all templates
templateFiles := []string{ templateFiles := []string{
@ -78,11 +86,24 @@ func New(cfg *config.Config, database *db.Database) *Admin {
} }
for _, tf := range templateFiles { for _, tf := range templateFiles {
// Create a clone of the base template // Read template content from embedded filesystem
t, err := template.Must(baseTemplate.Clone()).ParseFiles(filepath.Join(templateDir, tf)) content, err := templateFS.ReadFile("templates/" + tf)
if err != nil { if err != nil {
panic(err) panic(err)
} }
// Create a clone of the base template
t, err := baseTemplate.Clone()
if err != nil {
panic(err)
}
// Parse the template content
t, err = t.Parse(string(content))
if err != nil {
panic(err)
}
templates[tf] = t templates[tf] = t
} }