2019-11-15 03:03:56 +00:00
|
|
|
package responses
|
|
|
|
|
|
|
|
import (
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
2019-11-26 19:17:01 +00:00
|
|
|
|
|
|
|
"git.kirsle.net/apps/gophertype/pkg/console"
|
2019-11-15 03:03:56 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// RenderTemplate renders a Go HTML template.
|
|
|
|
// The io.Writer can be an http.ResponseWriter.
|
2019-11-15 04:58:55 +00:00
|
|
|
func RenderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, vars interface{}) error {
|
2019-11-26 03:55:28 +00:00
|
|
|
if vars == nil {
|
|
|
|
vars = NewTemplateVars(w, r)
|
|
|
|
}
|
|
|
|
|
2019-11-15 03:03:56 +00:00
|
|
|
// Look for the built-in template.
|
2019-11-26 19:17:01 +00:00
|
|
|
b, err := GetFile(tmpl)
|
|
|
|
if err == nil {
|
2019-11-15 04:58:55 +00:00
|
|
|
t, err := template.New(tmpl).Funcs(TemplateFuncs(r)).Parse(string(b))
|
2019-11-15 03:03:56 +00:00
|
|
|
if err != nil {
|
2019-11-26 19:17:01 +00:00
|
|
|
console.Error("RenderTemplate: bundled template '%s': %s", tmpl, err)
|
2019-11-15 04:58:55 +00:00
|
|
|
return err
|
2019-11-15 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We found the template. Can we find the layout html?
|
|
|
|
if layout, err := GetFile(".layout.gohtml"); err == nil {
|
|
|
|
_, err := t.New("layout").Parse(string(layout))
|
|
|
|
if err != nil {
|
2019-11-26 19:17:01 +00:00
|
|
|
console.Error("RenderTemplate(.layout.gohtml): %s", err)
|
2019-11-15 03:03:56 +00:00
|
|
|
}
|
|
|
|
} else {
|
2019-11-26 19:17:01 +00:00
|
|
|
console.Error("RenderTemplate: .layout.gohtml not found to wrap %s", tmpl)
|
2019-11-15 03:03:56 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 19:17:01 +00:00
|
|
|
console.Debug("Render Templ: %s", tmpl)
|
2019-11-15 03:03:56 +00:00
|
|
|
if err := t.ExecuteTemplate(w, "layout", vars); err != nil {
|
2019-11-26 19:17:01 +00:00
|
|
|
console.Error("RenderTemplate(%s): %s", tmpl, err)
|
2019-11-15 03:03:56 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-11-26 19:17:01 +00:00
|
|
|
Panic(w, http.StatusInternalServerError, err.Error())
|
2019-11-15 03:03:56 +00:00
|
|
|
return nil
|
|
|
|
}
|