Building a simple template cache
This commit is contained in:
parent
10d4172f3c
commit
3eb7a210b2
@ -3,14 +3,49 @@ package render
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// renderTemplate renders a HTML template file
|
var templateCache = make(map[string]*template.Template)
|
||||||
func RenderTemplate(w http.ResponseWriter, tmpl string) {
|
|
||||||
parsedTemplate, _ := template.ParseFiles("./templates/"+tmpl, "./templates/base.layout.tmpl")
|
// RenderTemplate renders a HTML template file
|
||||||
err := parsedTemplate.Execute(w, nil)
|
func RenderTemplate(w http.ResponseWriter, t string) {
|
||||||
|
var tmpl *template.Template
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// 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)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("error parsing template:", err)
|
log.Println(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tmpl = templateCache[t]
|
||||||
|
|
||||||
|
// use the template
|
||||||
|
err = tmpl.Execute(w, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func createTemplateCache(t string) error {
|
||||||
|
templates := []string{
|
||||||
|
fmt.Sprintf("./templates/%s", t),
|
||||||
|
"./templates/base.layout.tmpl",
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse the template
|
||||||
|
tmpl, err := template.ParseFiles(templates...)
|
||||||
|
if err != err {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// add template to cache
|
||||||
|
templateCache[t] = tmpl
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user