dati

A Go library/binary to parse & execute data against template langauges.
git clone git://src.gearsix.net/dati
Log | Files | Refs | Atom | README | LICENSE

commit 2cd00c4bc3d594b27ada7f4dd7566d87cd7b8df8
parent 98705b58667c14f53b298606582bb1f34e67eef9
Author: gearsix <gearsix@tuta.io>
Date:   Tue, 16 Feb 2021 18:07:16 +0000

added template.go

- parsing for text/template & html/template templates including
partials

Diffstat:
Msrc/data.go | 2+-
Msrc/suti.go | 10++++++++++
Asrc/template.go | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 73 insertions(+), 1 deletion(-)

diff --git a/src/data.go b/src/data.go @@ -80,7 +80,7 @@ func LoadData(lang string, in io.Reader) (d data, e error) { e = fmt.Errorf("invalid json") } } else { - e = fmt.Errorf("%s is not a supported data language", lang) + e = fmt.Errorf("'%s' is not a supported data language", lang) } return diff --git a/src/suti.go b/src/suti.go @@ -26,8 +26,18 @@ func init() { func main() { options := parseArgs(os.Args[1:]) + _ = LoadDataFiles(options.DataPaths...) _ = LoadDataFiles(options.GlobalDataPaths...) + + templates := make([]template, 0) + for _, r := range options.RootPaths { + if t, e := LoadTemplateFile(r, options.PartialPaths...); e != nil { + warn("unable to load templates (%s)", e) + } else { + templates = append(templates, t) + } + } return } diff --git a/src/template.go b/src/template.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + tmpl "text/template" + hmpl "html/template" +) + +type template interface{} + +func getTemplateType(path string) string { + return strings.TrimPrefix(filepath.Ext(path), ".") +} + +func LoadTemplateFile(root string, partials ...string) (t template, e error) { + if len(root) == 0 { + e = fmt.Errorf("no root template specified") + } + if stat, err := os.Stat(root); err != nil { + e = err + } else if stat.IsDir() { + e = fmt.Errorf("root path must be a file, not a directory: %s", root) + } + if e != nil { + return + } + + ttype := getTemplateType(root) + + if ttype == "tmpl" || ttype == "gotmpl" { + var gotmpl *tmpl.Template + if gotmpl, e = tmpl.ParseFiles(root); e != nil { + return nil, e + } + for _, p := range partials { + ptype := getTemplateType(p) + if ptype == "tmpl" || ptype == "gotmpl" { + gotmpl, e = gotmpl.ParseFiles(p) + } + } + t = gotmpl + } else if ttype == "hmpl" || ttype == "gohmpl" { + var gohmpl *hmpl.Template + if gohmpl, e = hmpl.ParseFiles(root); e != nil { + return nil, e + } + for _, p := range partials { + ptype := getTemplateType(p) + if ptype == "tmpl" || ptype == "gotmpl" { + gohmpl, e = gohmpl.ParseFiles(p) + } + } + t = gohmpl + } else { + e = fmt.Errorf("'%s' is not a supported template language", ttype) + } + + return +}