Use constructor-like function to load templates

This commit is contained in:
2022-01-04 22:29:53 +01:00
parent 2bffc08630
commit 277686086e
2 changed files with 13 additions and 6 deletions
+6 -1
View File
@@ -12,7 +12,7 @@ import (
"code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/config" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/config"
"code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/ghost/v4api/httpclient" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/ghost/v4api/httpclient"
"code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/routes" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/routes"
_ "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/templates" "code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/templates"
) )
var Version = "nightly" var Version = "nightly"
@@ -52,6 +52,11 @@ func main() {
logrus.Fatal(err) logrus.Fatal(err)
} }
err = templates.Load()
if err != nil {
logrus.Fatal(err)
}
ghostClient := &httpclient.HTTPClient{ ghostClient := &httpclient.HTTPClient{
Addr: config.Content.Backend.Addr, Addr: config.Content.Backend.Addr,
Secured: config.Content.Backend.Secured, Secured: config.Content.Backend.Secured,
+7 -5
View File
@@ -24,14 +24,14 @@ var content embed.FS
var Templates *template.Template var Templates *template.Template
// Load embeded templates // Load embeded templates
func init() { func Load() (err error) {
Templates = template.New("") Templates = template.New("")
Templates.Funcs(UseFuncs()) Templates.Funcs(UseFuncs())
tmplNames, err := fs.Glob(content, "*.go.tmpl") tmplNames, err := fs.Glob(content, "*.go.tmpl")
if err != nil { if err != nil {
panic(err) return fmt.Errorf("cannot match templates names using glob, %w", err)
} }
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
@@ -42,21 +42,23 @@ func init() {
tmplContent, err := content.Open(name) tmplContent, err := content.Open(name)
if err != nil { if err != nil {
panic(err) return fmt.Errorf("cannot open template content, name:%s, %w", name, err)
} }
size, err := buf.ReadFrom(tmplContent) size, err := buf.ReadFrom(tmplContent)
if err != nil { if err != nil {
panic(err) return fmt.Errorf("cannot read template content, name:%s, %w", name, err)
} }
tmpl, err := Templates.New(name).Parse(buf.String()) tmpl, err := Templates.New(name).Parse(buf.String())
if err != nil { if err != nil {
panic(err) return fmt.Errorf("cannot parse template, name:%s, %w", name, err)
} }
logrus.Debugf("Found template: %s, size:%d", tmpl.Name(), size) logrus.Debugf("Found template: %s, size:%d", tmpl.Name(), size)
} }
logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates()) logrus.Debugf("Templates loading complete%s", Templates.DefinedTemplates())
return
} }
// MustLookup wraps lookup function for the root template namespace // MustLookup wraps lookup function for the root template namespace