1
0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-11-08 14:19:20 +01:00
kiln/templates.go
2020-11-20 12:07:38 -05:00

106 lines
2.4 KiB
Go

package main
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
)
// 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{},
}
// Load default templates
t.LoadTemplate("/index.gmi", index_gmi)
t.LoadTemplate("/page.gmi", page_gmi)
t.LoadTemplate("/feed.gmi", feed_gmi)
t.LoadTemplate("/output.html", output_html)
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.
func (t *Templates) LoadTemplate(path string, content string) {
tmpl := template.New(path)
tmpl.Funcs(t.funcs)
template.Must(tmpl.Parse(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, string(b))
}
return nil
})
}
// FindTemplate searches recursively for a template for the given path.
func (t *Templates) FindTemplate(path string, tmpl string) *template.Template {
for {
tmplPath := filepath.Join(path, tmpl)
if t, ok := t.tmpls[tmplPath]; ok {
return t
}
slash := path == "/"
path = filepath.Dir(path)
if slash && path == "/" {
break
}
}
return nil
}
// Default index template
const index_gmi = `# Index of {{ .Path }}
{{ range .Dirs }}=> {{ .Path }}
{{ end -}}
{{ range .Pages }}=> {{ .Path }}
{{ end -}}`
// Default page template
const page_gmi = `# {{ .Title }}
{{ .Content }}`
// Default feed template
const feed_gmi = `# {{ .Title }}
Last updated at {{ .Updated.Format "2006-01-02" }}
{{ range .Entries }}=> {{ .Path }} {{ .Date.Format "2006-01-02" }} {{ .Title }}
{{ end -}}`
// Default template for html output
const output_html = `<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ .Title }}</title>
{{ .Content }}`