1
0
Fork 0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-05-14 16:36:04 +02:00
kiln/templates.go
2021-05-01 14:11:41 -04:00

96 lines
2.2 KiB
Go

package main
import (
htemplate "html/template"
"io"
"io/ioutil"
"os"
pathpkg "path"
"path/filepath"
"strings"
"text/template"
)
// Template represents a template.
type Template interface {
Execute(io.Writer, interface{}) error
}
// Templates contains site templates.
type Templates struct {
tmpls map[string]Template
funcs map[string]interface{}
}
// NewTemplates returns a new Templates with the default templates.
func NewTemplates() *Templates {
t := &Templates{
tmpls: map[string]Template{},
}
return t
}
// Funcs sets the functions available to newly created templates.
func (t *Templates) Funcs(funcs map[string]interface{}) {
t.funcs = funcs
}
// LoadTemplate loads a template from the provided path and content.
func (t *Templates) LoadTemplate(path string, content []byte) {
tmpl := template.New(path)
tmpl.Funcs(t.funcs)
template.Must(tmpl.Parse(string(content)))
t.tmpls[path] = tmpl
}
func (t *Templates) LoadHTMLTemplate(path string, content []byte) {
tmpl := htemplate.New(path)
tmpl.Funcs(htemplate.FuncMap(t.funcs))
htemplate.Must(tmpl.Parse(string(content)))
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)
if pathpkg.Ext(path) == ".html" {
t.LoadHTMLTemplate(path, b)
} else {
t.LoadTemplate(path, b)
}
}
return nil
})
}
// FindTemplate returns the template for the given path.
func (t *Templates) FindTemplate(path string, tmpl string) (Template, bool) {
tmplPath := pathpkg.Join(path, tmpl)
if t, ok := t.tmpls[tmplPath]; ok {
return t, true
}
if t, ok := t.tmpls[pathpkg.Join("/_default", tmpl)]; ok {
return t, true
}
// Failed to find template
return nil, false
}
// FindPartial returns the partial template of the given name.
func (t *Templates) FindPartial(name string) (Template, bool) {
if t, ok := t.tmpls[pathpkg.Join("/_partials", name)]; ok {
return t, true
}
return nil, false
}