Added embedded FS for static and templates

main
Drew Bednar 3 months ago
parent 83ac76795c
commit 514c24a768

@ -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)

@ -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]

@ -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

Loading…
Cancel
Save