2024-06-26 20:06:32 +00:00
|
|
|
package render
|
2024-06-26 19:56:58 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
2024-06-26 20:50:04 +00:00
|
|
|
"log"
|
2024-06-26 19:56:58 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2024-06-26 20:50:04 +00:00
|
|
|
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
|
|
|
|
|
|
|
|
// 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 {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tmpl = templateCache[t]
|
|
|
|
|
|
|
|
// use the template
|
|
|
|
err = tmpl.Execute(w, nil)
|
2024-06-26 19:56:58 +00:00
|
|
|
if err != nil {
|
2024-06-26 20:50:04 +00:00
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func createTemplateCache(t string) error {
|
|
|
|
templates := []string{
|
|
|
|
fmt.Sprintf("./templates/%s", t),
|
|
|
|
"./templates/base.layout.tmpl",
|
2024-06-26 19:56:58 +00:00
|
|
|
}
|
2024-06-26 20:50:04 +00:00
|
|
|
|
|
|
|
// parse the template
|
|
|
|
tmpl, err := template.ParseFiles(templates...)
|
|
|
|
if err != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// add template to cache
|
|
|
|
templateCache[t] = tmpl
|
|
|
|
return nil
|
2024-06-26 19:56:58 +00:00
|
|
|
}
|