diff --git a/cmd/ratchetd/main.go b/cmd/ratchetd/main.go index f3d9aa0..d54a646 100644 --- a/cmd/ratchetd/main.go +++ b/cmd/ratchetd/main.go @@ -47,7 +47,8 @@ func main() { // Close db connection before exiting main. defer db.Close() - tc, err := server.InitTemplateCache() + //tc, err := server.InitTemplateCache() + tc, err := server.InitFSTemplateCache() if err != nil { slog.Error(err.Error()) os.Exit(1) diff --git a/internal/server/templates.go b/internal/server/templates.go index 23fb945..0014d77 100644 --- a/internal/server/templates.go +++ b/internal/server/templates.go @@ -5,11 +5,13 @@ import ( "database/sql" "fmt" "html/template" + "io/fs" "net/http" "path/filepath" "time" "git.runcible.io/learning/ratchet/internal/model" + "git.runcible.io/learning/ratchet/ui" "github.com/alexedwards/scs/v2" "github.com/justinas/nosurf" ) @@ -123,6 +125,37 @@ func InitTemplateCache() (*TemplateCache, error) { return &cache, nil } +func InitFSTemplateCache() (*TemplateCache, error) { + cache := TemplateCache{} + + pages, err := fs.Glob(ui.Files, "html/pages/*.tmpl") + if err != nil { + return nil, err + } + + for _, page := range pages { + name := filepath.Base(page) + + // Create a slice container the filepath patterns for the templates we + // want to parse + patterns := []string{ + "html/base.go.tmpl", + "html/partials/*.tmpl", + page, + } + + tmpl, err := template.New(name).Funcs(templateFuncMap).ParseFS(ui.Files, patterns...) + if err != nil { + return nil, err + } + + cache[name] = tmpl + + } + + return &cache, nil +} + func renderTemplate(w http.ResponseWriter, r *http.Request, tc *TemplateCache, status int, page string, data templateData) { cache := *tc ts, ok := cache[page] diff --git a/ui/efs.go b/ui/efs.go index 346a707..744f5b6 100644 --- a/ui/efs.go +++ b/ui/efs.go @@ -7,8 +7,11 @@ import "embed" // to the .go file it is in. You can only embed on global variables at a package // level. Paths cannot contain . or .. or begin with / So you are effectively // restricted to embedding files within the same directory as the .go file. +// You can provide multiple passes "static/css" "static/img" "static/js" to help with +// avoiding shipping things like a PostCSS(tailwind) css file. +// Can also us static/css/*.css. "all:static" will embed . and _ files too. // Lastly the embedded file system is always rooted in the directory that contains // the embed directive. So in this example the root is in our ui dir. -//go:embed "static" +//go:embed "static" "html" var Files embed.FS