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 {
// Check if the template exists already in the cache map log.Fatal(err)
_, inMap := templateCache[t] }
if !inMap { // get requested template from cache
// need to create the template t, ok := tc[tmpl]
log.Printf("Create template cache for the template %s\n", t) if !ok {
err = createTemplateCache(t) log.Fatal(err)
if err != nil {
log.Println(err)
}
} }
tmpl = templateCache[t]
// use the template // Write to a buffer to make sure that the template can be read and
err = tmpl.Execute(w, nil) // written successfully
buf := new(bytes.Buffer)
err = t.Execute(buf, nil)
if err != nil {
log.Println(err)
}
// render the template
_, 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
}
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
} }
// add template to cache return myCache, nil
templateCache[t] = tmpl
return nil
} }