Building a template cache
This commit is contained in:
@@ -1,17 +1,75 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var functions = template.FuncMap{}
|
||||
|
||||
// RenderTemplate renders templates using html/template
|
||||
func RenderTemplate(w http.ResponseWriter, tmpl string) {
|
||||
parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl)
|
||||
err := parsedTemplate.Execute(w, nil)
|
||||
|
||||
tc, err := CreateTemplateCache()
|
||||
if err != nil {
|
||||
fmt.Println("error parsing template:", err)
|
||||
return
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
t, ok := tc[tmpl]
|
||||
if !ok {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
_ = t.Execute(buf, nil)
|
||||
|
||||
_, err = buf.WriteTo(w)
|
||||
if err != nil {
|
||||
fmt.Println("Error writing template to browser", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// CreateTemplateCache creates atemplate cache as a map
|
||||
func CreateTemplateCache() (map[string]*template.Template, error) {
|
||||
|
||||
myCache := map[string]*template.Template{}
|
||||
|
||||
pages, err := filepath.Glob("./templates/*.tmpl")
|
||||
if err != nil {
|
||||
return myCache, err
|
||||
}
|
||||
|
||||
for _, page := range pages {
|
||||
name := filepath.Base(page)
|
||||
fmt.Println("Page is currently", page)
|
||||
|
||||
ts, err := template.New(name).Funcs(functions).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
|
||||
|
||||
}
|
||||
|
||||
return myCache, nil
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user