galley/galley_templates.go

53 lines
1.3 KiB
Go

package main
import (
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
)
// cache templates on initialization
var templates map[string]*template.Template
// Load templates on program initialisation
func init() {
if templates == nil {
templates = make(map[string]*template.Template)
}
templatesDir := "tmpl/"
layouts, err := filepath.Glob(templatesDir + "layouts/*.html")
if err != nil {
log.Fatal(err)
}
includes, err := filepath.Glob(templatesDir + "includes/*.html")
if err != nil {
log.Fatal(err)
}
// Generate our templates map from our layouts/ and includes/ directories
for _, layout := range layouts {
files := append(includes, layout)
templates[filepath.Base(layout)] = template.Must(template.ParseFiles(files...))
}
}
// renderTemplate is a wrapper around template.ExecuteTemplate.
func RenderTemplate(w http.ResponseWriter, name string, p *Page) {
// Ensure the template exists in the map.
tmpl, ok := templates[name+".html"]
if !ok {
http.Error(w, fmt.Errorf("The template %s does not exist.", name).Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := tmpl.ExecuteTemplate(w, "base", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}