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 package render
import ( import (
"fmt" "bytes"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"path/filepath"
) )
var templateCache = make(map[string]*template.Template)
// RenderTemplate renders a HTML template file // RenderTemplate renders a HTML template file
func RenderTemplate(w http.ResponseWriter, t string) { func RenderTemplate(w http.ResponseWriter, tmpl string) {
var tmpl *template.Template // create a template cache
var err error 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 // Write to a buffer to make sure that the template can be read and
_, inMap := templateCache[t] // written successfully
if !inMap { buf := new(bytes.Buffer)
// need to create the template err = t.Execute(buf, nil)
log.Printf("Create template cache for the template %s\n", t)
err = createTemplateCache(t)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
}
tmpl = templateCache[t]
// use the template // render the template
err = tmpl.Execute(w, nil) _, err = buf.WriteTo(w)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
} }
func createTemplateCache(t string) error { func createTemplateCache() (map[string]*template.Template, error) {
templates := []string{ myCache := map[string]*template.Template{}
fmt.Sprintf("./templates/%s", t),
"./templates/base.layout.tmpl", // 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 // range through all files ending with *page.tmpl
tmpl, err := template.ParseFiles(templates...) for _, page := range pages {
if err != err { name := filepath.Base(page)
return err ts, err := template.New(name).ParseFiles(page)
if err != nil {
return myCache, err
} }
// add template to cache matches, err := filepath.Glob("./templates/*.layout.tmpl")
templateCache[t] = tmpl if err != nil {
return 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
} }