2020-09-29 22:42:27 +02:00
|
|
|
package main
|
|
|
|
|
2020-11-20 18:07:38 +01:00
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2020-11-22 21:51:07 +01:00
|
|
|
pathpkg "path"
|
2020-11-20 18:07:38 +01:00
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"text/template"
|
|
|
|
)
|
2020-11-11 01:33:45 +01:00
|
|
|
|
2020-11-20 18:07:38 +01:00
|
|
|
// Templates contains site templates.
|
|
|
|
type Templates struct {
|
|
|
|
tmpls map[string]*template.Template
|
|
|
|
funcs template.FuncMap
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewTemplates returns a new Templates with the default templates.
|
|
|
|
func NewTemplates() *Templates {
|
|
|
|
t := &Templates{
|
|
|
|
tmpls: map[string]*template.Template{},
|
|
|
|
}
|
|
|
|
return t
|
|
|
|
}
|
|
|
|
|
|
|
|
// Funcs sets the functions available to newly created templates.
|
|
|
|
func (t *Templates) Funcs(funcs template.FuncMap) {
|
|
|
|
t.funcs = funcs
|
|
|
|
}
|
|
|
|
|
|
|
|
// LoadTemplate loads a template from the provided path and content.
|
2021-02-27 21:56:23 +01:00
|
|
|
func (t *Templates) LoadTemplate(path string, content []byte) {
|
2020-11-20 18:07:38 +01:00
|
|
|
tmpl := template.New(path)
|
|
|
|
tmpl.Funcs(t.funcs)
|
2021-02-27 21:56:23 +01:00
|
|
|
template.Must(tmpl.Parse(string(content)))
|
2020-11-20 18:07:38 +01:00
|
|
|
t.tmpls[path] = tmpl
|
|
|
|
}
|
|
|
|
|
|
|
|
// Load loads templates from the provided directory
|
|
|
|
func (t *Templates) Load(dir string) error {
|
|
|
|
return filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if info.Mode().IsRegular() {
|
|
|
|
b, err := ioutil.ReadFile(path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Remove directory from beginning of path
|
|
|
|
path = strings.TrimPrefix(path, dir)
|
2021-02-27 21:56:23 +01:00
|
|
|
t.LoadTemplate(path, b)
|
2020-11-20 18:07:38 +01:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2020-09-29 22:42:27 +02:00
|
|
|
|
2021-04-21 20:39:13 +02:00
|
|
|
// FindTemplate returns the template for the given path.
|
|
|
|
func (t *Templates) FindTemplate(path string, tmpl string) (*template.Template, bool) {
|
2020-11-22 21:51:07 +01:00
|
|
|
tmplPath := pathpkg.Join(path, tmpl)
|
|
|
|
if t, ok := t.tmpls[tmplPath]; ok {
|
2021-04-21 20:39:13 +02:00
|
|
|
return t, true
|
2020-11-20 18:07:38 +01:00
|
|
|
}
|
2021-03-21 04:17:58 +01:00
|
|
|
if t, ok := t.tmpls[pathpkg.Join("/_default", tmpl)]; ok {
|
2021-04-21 20:39:13 +02:00
|
|
|
return t, true
|
2021-03-21 04:17:58 +01:00
|
|
|
}
|
2021-04-21 20:39:13 +02:00
|
|
|
// Failed to find template
|
|
|
|
return nil, false
|
2020-11-20 18:07:38 +01:00
|
|
|
}
|