Currently, I have a map[string]*template.Template
, which stores each individual template. I load them like so:
func Load(templates fs.FS) (map[string]*template.Template, error) {
pages := []string{"home", "login", "signup", "dashboard"}
partials := []string{"account-form", "user-details"}
tmpls := make(map[string]*template.Template)
for _, page := range pages {
tmpl := template.New("layout.tmpl")
tmpl, err := tmpl.ParseFS(templates, "layouts/layout.tmpl", "pages/"+page+".tmpl")
if err != nil {
return nil, err
}
for _, partial := range partials {
tmpl, err = tmpl.ParseFS(templates, "partials/"+partial+".tmpl")
if err != nil {
return nil, err
}
}
tmpls[page] = tmpl
}
return tmpls, nil
}
This does the job, since I can then execute a template like so: tmpls["home"].Execute(w, data)
.
However, I’m not sure this is the most efficient way of doing this. I read you can hold it all in a single *template.Template
variable.
I tried doing something like:
func Load(templates fs.FS) (*template.Template, error) {
tmpl, err := template.New("layout").ParseFS(templates, "layouts/layout.tmpl", "pages/*.tmpl", "partials/*.tmpl")
return tmpl, err
}
// somewhere else
// executing template
tmpl.ExecuteTemplate(w, "home.tmpl", data)
But all I got is a blank page.
Here is what my layout.tmpl file looks like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=">
<title>{{ block "page-title" . }} Some Website {{ end }}</title>
<link rel="stylesheet" href="/assets/css/styles.css">
</head>
<body>
<header>...</header>
<main>{{ template "main" . }}</main>
<footer>...</footer>
</body>
Here is what my home.tmpl file looks like:
{{ define "main" }}
<section>Some content...</section>
{{ end }}
How can I achieve this? Any help is appreciated.