Add dev flag to indicate development runs

Used to reload the templates on each page view.
This commit is contained in:
Las Zenow 2020-12-03 12:58:37 +00:00
parent 1536d97d8d
commit fe36b1d23c
2 changed files with 46 additions and 3 deletions

View file

@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"io"
"net/http"
"path"
"strings"
@ -53,9 +54,13 @@ func GetStatus(h handler) Status {
return s
}
type TemplateExecutor interface {
ExecuteTemplate(io.Writer, string, interface{}) error
}
type Template struct {
html *html_tmpl.Template
opds *txt_tmpl.Template
html TemplateExecutor
opds TemplateExecutor
}
func InitTemplate(assetsPath string) *Template {
@ -78,6 +83,38 @@ func InitTemplate(assetsPath string) *Template {
return &t
}
type DevTemplateExecutor struct {
assetsPath string
tpe string
}
func InitDevTemplate(assetsPath string) *Template {
return &Template{
html: DevTemplateExecutor{assetsPath, "html"},
opds: DevTemplateExecutor{assetsPath, "txt"},
}
}
func (e DevTemplateExecutor) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
templatePath := path.Join(e.assetsPath, "templates")
file := path.Join(templatePath, name)
var t TemplateExecutor
switch e.tpe {
case "html":
included_files := []string{file}
for _, f := range []string{"header.html", "footer.html", "book_list.html"} {
included_files = append(included_files, path.Join(templatePath, f))
}
t = html_tmpl.Must(html_tmpl.New("html").Funcs(html_tmpl.FuncMap{
"strings_join": strings.Join,
}).ParseFiles(included_files...))
case "txt":
t = txt_tmpl.Must(txt_tmpl.ParseFiles(file))
}
return t.ExecuteTemplate(wr, name, data)
}
func loadJson(w http.ResponseWriter, tmpl string, data interface{}) error {
var res []byte
var err error