diff --git a/boot.go b/boot.go index 941ef3e..7e36092 100644 --- a/boot.go +++ b/boot.go @@ -16,5 +16,10 @@ func boot_system() (*lib.Environment, error) { if err != nil { return env, err } + env.Template, err = lib.LoadTemplates(`templates`) + if err != nil { + return env, err + } + return env, nil } diff --git a/lib/environment.go b/lib/environment.go index 102db2e..e51e73e 100644 --- a/lib/environment.go +++ b/lib/environment.go @@ -2,6 +2,7 @@ package lib import ( "io/ioutil" + "text/template" "gopkg.in/yaml.v1" ) @@ -14,6 +15,8 @@ type Environment struct { Config *Settings // the database connection pool DB *Database + // the base template system + Template *template.Template } func LoadConfiguration() (*Settings, error) { diff --git a/lib/template.go b/lib/template.go new file mode 100644 index 0000000..38e4af2 --- /dev/null +++ b/lib/template.go @@ -0,0 +1,47 @@ +package lib + +import ( + "log" + "io/ioutil" + "os" + "path/filepath" + "text/template" +) + +type fileList struct { + len_base int + t *template.Template +} + +// load all templates found as childs of the path +func LoadTemplates(path string) (*template.Template, error) { + f := &fileList{len(path), &template.Template{}} + + err := filepath.Walk(path, f.scanFile) + if err != nil { + return nil, err + } + return f.t, nil +} + +func (f *fileList) scanFile(path string, info os.FileInfo, err error) error { + if err != nil { log.Println(`Error with file:`, path, `-`, err) } + + if info.IsDir() { + log.Print(`Scanning '`, path, `' for templates`) + } + if !info.IsDir() && path[len(path) - 5:] == `.tmpl` { + name := path[f.len_base + 1 : len(path) - 5] + log.Println(`Adding:`, name) + f.t.New(name).Parse(read_file_content(path)) + } + return nil +} + +func read_file_content(path string) string { + content, err := ioutil.ReadFile(path) + if err != nil { + return "" + } + return string(content) +}