kiln/templates.go
2021-04-20 16:00:39 -04:00

92 lines
2.1 KiB
Go

package main
import (
"embed"
"io/ioutil"
"log"
"os"
pathpkg "path"
"path/filepath"
"strings"
"text/template"
)
//go:embed templates config.toml
var builtin embed.FS
// 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
}
// LoadDefault loads the default templates.
// Should be called after Funcs.
func (t *Templates) LoadDefault() {
t.loadDefault("index.gmi")
t.loadDefault("page.gmi")
t.loadDefault("atom.xml")
t.loadDefault("output.html")
}
func (t *Templates) loadDefault(name string) {
b, err := builtin.ReadFile("templates/" + name)
if err != nil {
panic(err)
}
t.LoadTemplate("/_default/"+name, b)
}
// 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
}
// 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)
t.LoadTemplate(path, b)
}
return nil
})
}
// FindTemplate returns a template for the given path, or the default template if it does not exist.
func (t *Templates) FindTemplate(path string, tmpl string) *template.Template {
tmplPath := pathpkg.Join(path, tmpl)
if t, ok := t.tmpls[tmplPath]; ok {
return t
}
if t, ok := t.tmpls[pathpkg.Join("/_default", tmpl)]; ok {
return t
}
log.Fatalf("failed to find template %q", tmpl)
return nil
}