Add support for directory structured templates

This commit is contained in:
ssobolewski 2018-03-31 19:23:57 -06:00
parent 6a63c7cc76
commit 7ed387dee5
1 changed files with 58 additions and 1 deletions

View File

@ -5,6 +5,8 @@ import (
"net/http"
"os"
"path"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"time"
@ -65,15 +67,67 @@ func (s *Server) wrapper(handle func(c *Context)) http.HandlerFunc {
}
}
// This is a bit different then the standard template.parseFiles code in that it gives us hiarchial templates
// header.html
// mydirectory/service.html ...
func (s *Server) parseTemplates(t *template.Template, filenames ...string) (*template.Template, error) {
//if err := t.checkCanParse(); err != nil {
// return nil, err
//}
if len(filenames) == 0 {
// Not really a problem, but be consistent.
return nil, fmt.Errorf("html/template: no files named in call to ParseFiles")
}
for _, filename := range filenames {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
data := string(b)
name := strings.TrimPrefix(filename, s.templates+"/")
log.Println("Template:", name)
// First template becomes return value if not already defined,
// and we use that one for subsequent New calls to associate
// all the templates together. Also, if this file has the same name
// as t, this file becomes the contents of t, so
// t, err := New(name).Funcs(xxx).ParseFiles(name)
// works. Otherwise we create a new template associated with t.
var tmpl *template.Template
if t == nil {
t = template.New(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.New(name)
}
_, err = tmpl.Parse(data)
if err != nil {
return nil, err
}
}
return t, nil
}
func (s *Server) loadTemplates() *template.Template {
tmpl := template.New("")
err := filepath.Walk(path.Join(s.path, s.templates), func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".html") {
_,err := s.parseTemplates(tmpl, path)
if err != nil {
log.Println(err)
}
/*
_, err = tmpl.ParseFiles(path)
if err != nil {
log.Println(err)
}
*/
}
return err
})
@ -97,7 +151,10 @@ func (s *Server) getTemplates() *template.Template {
}
func (s *Server) render(w http.ResponseWriter, tmpl string, content interface{}) {
s.getTemplates().ExecuteTemplate(w, tmpl, content)
err := s.getTemplates().ExecuteTemplate(w, tmpl, content)
if err != nil {
log.Warn(err)
}
}
func (s *Server) reply(w http.ResponseWriter, msg string) {