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

99 lines
2.1 KiB
Go
Raw Normal View History

2024-06-26 20:06:32 +00:00
package render
2024-06-26 19:56:58 +00:00
import (
2024-06-27 11:19:38 +00:00
"bytes"
2024-06-30 14:41:46 +00:00
"go-udemy-web-1/internal/config"
"go-udemy-web-1/internal/models"
2024-06-26 19:56:58 +00:00
"html/template"
2024-06-26 20:50:04 +00:00
"log"
2024-06-26 19:56:58 +00:00
"net/http"
2024-06-27 11:19:38 +00:00
"path/filepath"
"github.com/justinas/nosurf"
2024-06-26 19:56:58 +00:00
)
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, r *http.Request) *models.TemplateData {
td.Flash = app.Session.PopString(r.Context(), "flash")
td.Warning = app.Session.PopString(r.Context(), "warning")
td.Error = app.Session.PopString(r.Context(), "error")
td.CSRFToken = nosurf.Token(r)
return td
}
2024-06-26 20:50:04 +00:00
// RenderTemplate renders a HTML template file
func RenderTemplate(w http.ResponseWriter, r *http.Request, 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()
2024-06-27 11:19:38 +00:00
}
2024-06-27 11:19:38 +00:00
// get requested template from cache
t, ok := tc[tmpl]
if !ok {
log.Fatal("Could not get template from template cache")
2024-06-26 20:50:04 +00:00
}
2024-06-27 11:19:38 +00:00
// Write to a buffer to make sure that the template can be read and
// written successfully
buf := new(bytes.Buffer)
td = AddDefaultData(td, r)
err := t.Execute(buf, td)
2024-06-27 11:19:38 +00:00
if err != nil {
log.Println(err)
}
// render the template
_, err = buf.WriteTo(w)
2024-06-26 19:56:58 +00:00
if err != nil {
2024-06-26 20:50:04 +00:00
log.Println(err)
}
}
func CreateTemplateCache() (map[string]*template.Template, error) {
2024-06-27 11:19:38 +00:00
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
2024-06-26 19:56:58 +00:00
}
2024-06-26 20:50:04 +00:00
2024-06-27 11:19:38 +00:00
// 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
2024-06-26 20:50:04 +00:00
}
2024-06-27 11:19:38 +00:00
return myCache, nil
2024-06-26 19:56:58 +00:00
}