Refactor template loading around the handler
This commit is contained in:
parent
d40dc21627
commit
5517da6a69
9 changed files with 40 additions and 42 deletions
|
@ -4,8 +4,6 @@ import (
|
|||
html_tmpl "html/template"
|
||||
txt_tmpl "text/template"
|
||||
|
||||
log "github.com/cihub/seelog"
|
||||
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
@ -47,16 +45,16 @@ func GetStatus(h handler) Status {
|
|||
}
|
||||
|
||||
type Template struct {
|
||||
tmpl_html *html_tmpl.Template
|
||||
tmpl_rss *txt_tmpl.Template
|
||||
tmpl_opds *txt_tmpl.Template
|
||||
html *html_tmpl.Template
|
||||
rss *txt_tmpl.Template
|
||||
opds *txt_tmpl.Template
|
||||
}
|
||||
|
||||
func InitTemplate(assetsPath string) *Template {
|
||||
var t Template
|
||||
templatePath := path.Join(assetsPath, "templates")
|
||||
|
||||
t.tmpl_html = html_tmpl.Must(html_tmpl.ParseFiles(
|
||||
t.html = html_tmpl.Must(html_tmpl.ParseFiles(
|
||||
path.Join(templatePath, "header.html"),
|
||||
path.Join(templatePath, "footer.html"),
|
||||
path.Join(templatePath, "404.html"),
|
||||
|
@ -76,12 +74,12 @@ func InitTemplate(assetsPath string) *Template {
|
|||
path.Join(templatePath, "help.html"),
|
||||
))
|
||||
|
||||
t.tmpl_rss = txt_tmpl.Must(txt_tmpl.ParseFiles(
|
||||
t.rss = txt_tmpl.Must(txt_tmpl.ParseFiles(
|
||||
path.Join(templatePath, "search.rss"),
|
||||
path.Join(templatePath, "news.rss"),
|
||||
))
|
||||
|
||||
t.tmpl_opds = txt_tmpl.Must(txt_tmpl.ParseFiles(
|
||||
t.opds = txt_tmpl.Must(txt_tmpl.ParseFiles(
|
||||
path.Join(templatePath, "index.opds"),
|
||||
path.Join(templatePath, "search.opds"),
|
||||
))
|
||||
|
@ -89,25 +87,6 @@ func InitTemplate(assetsPath string) *Template {
|
|||
return &t
|
||||
}
|
||||
|
||||
func (t Template) load(h handler, tmpl string, data interface{}) {
|
||||
var err error
|
||||
fmt := h.r.FormValue("fmt")
|
||||
switch fmt {
|
||||
case "rss":
|
||||
err = t.tmpl_rss.ExecuteTemplate(h.w, tmpl+".rss", data)
|
||||
case "opds":
|
||||
err = t.tmpl_opds.ExecuteTemplate(h.w, tmpl+".opds", data)
|
||||
case "json":
|
||||
err = loadJson(h.w, tmpl, data)
|
||||
default:
|
||||
err = t.tmpl_html.ExecuteTemplate(h.w, tmpl+".html", data)
|
||||
}
|
||||
if err != nil {
|
||||
t.tmpl_html.ExecuteTemplate(h.w, "404.html", data)
|
||||
log.Warn("An error ocurred loading the template ", tmpl, ".", fmt, ": ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func loadJson(w http.ResponseWriter, tmpl string, data interface{}) error {
|
||||
var res []byte
|
||||
var err error
|
||||
|
|
Reference in a new issue