Building a more complex template cache

This commit is contained in:
Muyao CHEN 2024-06-27 13:19:38 +02:00
parent 3eb7a210b2
commit 2391f5a160

View File

@ -1,51 +1,72 @@
package render
import (
"fmt"
"bytes"
"html/template"
"log"
"net/http"
"path/filepath"
)
var templateCache = make(map[string]*template.Template)
// RenderTemplate renders a HTML template file
func RenderTemplate(w http.ResponseWriter, t string) {
var tmpl *template.Template
var err error
func RenderTemplate(w http.ResponseWriter, tmpl string) {
// create a template cache
tc, err := createTemplateCache()
if err != nil {
log.Fatal(err)
}
// get requested template from cache
t, ok := tc[tmpl]
if !ok {
log.Fatal(err)
}
// Check if the template exists already in the cache map
_, inMap := templateCache[t]
if !inMap {
// need to create the template
log.Printf("Create template cache for the template %s\n", t)
err = createTemplateCache(t)
// Write to a buffer to make sure that the template can be read and
// written successfully
buf := new(bytes.Buffer)
err = t.Execute(buf, nil)
if err != nil {
log.Println(err)
}
}
tmpl = templateCache[t]
// use the template
err = tmpl.Execute(w, nil)
// render the template
_, err = buf.WriteTo(w)
if err != nil {
log.Println(err)
}
}
func createTemplateCache(t string) error {
templates := []string{
fmt.Sprintf("./templates/%s", t),
"./templates/base.layout.tmpl",
func createTemplateCache() (map[string]*template.Template, error) {
myCache := map[string]*template.Template{}
// get all of the files named *.page.tmpl from ./templates
pages, err := filepath.Glob("./templates/*.page.tmpl")
if err != nil {
return myCache, err
}
// parse the template
tmpl, err := template.ParseFiles(templates...)
if err != err {
return err
// range through all files ending with *page.tmpl
for _, page := range pages {
name := filepath.Base(page)
ts, err := template.New(name).ParseFiles(page)
if err != nil {
return myCache, err
}
// add template to cache
templateCache[t] = tmpl
return nil
matches, err := filepath.Glob("./templates/*.layout.tmpl")
if err != nil {
return myCache, err
}
if len(matches) > 0 {
ts, err = ts.ParseGlob("./templates/*.layout.tmpl")
if err != nil {
return myCache, err
}
}
myCache[name] = ts
}
return myCache, nil
}