udemy-go-web-1/pkg/render/render.go

93 lines
1.9 KiB
Go

package render
import (
"bytes"
"go-udemy-web-1/pkg/config"
"go-udemy-web-1/pkg/models"
"html/template"
"log"
"net/http"
"path/filepath"
)
var app *config.AppConfig
// NewTemplates sets the config for the template package
func NewTemplates(a *config.AppConfig) {
app = a
}
// AddDefaultData adds default template data
func AddDefaultData(td *models.TemplateData) *models.TemplateData {
return td
}
// RenderTemplate renders a HTML template file
func RenderTemplate(w http.ResponseWriter, tmpl string, td *models.TemplateData) {
var tc map[string]*template.Template
if app.UseCache {
// get the template cache from the app config
tc = app.TemplateCahce
} else {
tc, _ = CreateTemplateCache()
}
// get requested template from cache
t, ok := tc[tmpl]
if !ok {
log.Fatal("Could not get template from template cache")
}
// Write to a buffer to make sure that the template can be read and
// written successfully
buf := new(bytes.Buffer)
td = AddDefaultData(td)
err := t.Execute(buf, td)
if err != nil {
log.Println(err)
}
// render the template
_, err = buf.WriteTo(w)
if err != nil {
log.Println(err)
}
}
func CreateTemplateCache() (map[string]*template.Template, error) {
myCache := map[string]*template.Template{}
// get all of the files named *.page.tmpl from ./templates
pages, err := filepath.Glob("./templates/*.page.tmpl")
if err != nil {
return myCache, err
}
// range through all files ending with *page.tmpl
for _, page := range pages {
name := filepath.Base(page)
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
}
return myCache, nil
}