diff options
author | Alan Pearce | 2024-05-07 15:24:42 +0200 |
---|---|---|
committer | Alan Pearce | 2024-05-07 15:24:42 +0200 |
commit | 64520c95ef7ad3042049ad1bfcad7f72f1ae1325 (patch) | |
tree | 38d928963fe18d5f677b500290ae2055a58f4058 /internal/server/templates.go | |
parent | e4fd32b04c1e3852bfd9a18e3afa5c1aea1ef9ea (diff) | |
download | searchix-64520c95ef7ad3042049ad1bfcad7f72f1ae1325.tar.lz searchix-64520c95ef7ad3042049ad1bfcad7f72f1ae1325.tar.zst searchix-64520c95ef7ad3042049ad1bfcad7f72f1ae1325.zip |
refactor: rely on html/template functionality more
Diffstat (limited to 'internal/server/templates.go')
-rw-r--r-- | internal/server/templates.go | 27 |
1 files changed, 11 insertions, 16 deletions
diff --git a/internal/server/templates.go b/internal/server/templates.go index 0b39729..71fc5c7 100644 --- a/internal/server/templates.go +++ b/internal/server/templates.go @@ -5,7 +5,6 @@ import ( "html" "html/template" "log/slog" - "os" "path" "path/filepath" "searchix/internal/options" @@ -35,15 +34,12 @@ var templateFuncs = template.FuncMap{ }, } -func loadTemplate(filename string) (*template.Template, error) { - text, err := os.ReadFile(filename) - if err != nil { - return nil, errors.WithMessage(err, "could not read template") - } - name, _ := strings.CutSuffix(path.Base(filename), ".gotmpl") - tpl := template.New(name) +func loadTemplate(filenames ...string) (*template.Template, error) { + tpl := template.New(path.Base(filenames[0])) + tpl.Funcs(templateFuncs) - _, err = tpl.Parse(string(text)) + + _, err := tpl.ParseFiles(filenames...) if err != nil { return nil, errors.WithMessage(err, "could not parse template") } @@ -55,7 +51,9 @@ func loadTemplates() (TemplateCollection, error) { templateDir := path.Join("frontend", "templates") templates := make(TemplateCollection, 0) - index, err := loadTemplate(path.Join(templateDir, "index.gotmpl")) + layoutFile := path.Join(templateDir, "index.gotmpl") + + index, err := loadTemplate(layoutFile) if err != nil { return nil, err } @@ -66,15 +64,12 @@ func loadTemplates() (TemplateCollection, error) { return nil, errors.WithMessage(err, "could not glob block templates") } for _, fullname := range templatePaths { - tpl, err := loadTemplate(fullname) + tpl, err := loadTemplate(fullname, layoutFile) if err != nil { return nil, err } - _, err = tpl.AddParseTree("index", index.Tree) - if err != nil { - return nil, errors.WithMessage(err, "could not add index template") - } - templates[tpl.Name()] = tpl + name, _ := strings.CutSuffix(path.Base(fullname), ".gotmpl") + templates[name] = tpl } return templates, nil |