Search for templates recursively

This commit is contained in:
adnano 2020-09-30 22:14:10 -04:00
parent 919cdd7556
commit e662a70990

31
main.go
View file

@ -22,11 +22,11 @@ const (
htmlDst = "dst.html" // html destination htmlDst = "dst.html" // html destination
indexPath = "index.gmi" // path used for index files indexPath = "index.gmi" // path used for index files
atomPath = "atom.xml" // path used for atom feeds atomPath = "atom.xml" // path used for atom feeds
tmplDir = "templates/" // templates directory tmplDir = "templates" // templates directory
atomTmpl = "atom.xml" // path to atom template atomTmpl = "/atom.xml" // path to atom template
indexTmpl = "index.gmi" // path to index template indexTmpl = "/index.gmi" // path to index template
pageTmpl = "page.gmi" // path to page template pageTmpl = "/page.gmi" // path to page template
htmlTmpl = "output.html" // path to html template htmlTmpl = "/output.html" // path to html template
) )
// site config // site config
@ -83,6 +83,23 @@ func loadTemplate(path string, content string) {
templates[path] = tmpl templates[path] = tmpl
} }
// findTemplate searches recursively for a template for the given path.
func findTemplate(path string, tmpl string) *template.Template {
for {
tmplPath := filepath.Join(path, tmpl)
if t, ok := templates[tmplPath]; ok {
return t
}
slash := path == "/"
path = filepath.Dir(path)
if slash && path == "/" {
break
}
}
// shouldn't happen
return nil
}
func run() error { func run() error {
// Load default templates // Load default templates
loadTemplate(atomTmpl, atom_xml) loadTemplate(atomTmpl, atom_xml)
@ -164,7 +181,7 @@ func manipulate(dir *Dir) error {
// Write the directory index file, if it doesn't exist // Write the directory index file, if it doesn't exist
if dir.index == nil { if dir.index == nil {
var b bytes.Buffer var b bytes.Buffer
tmpl := templates[indexTmpl] tmpl := findTemplate(dir.Permalink, indexTmpl)
if err := tmpl.Execute(&b, dir); err != nil { if err := tmpl.Execute(&b, dir); err != nil {
return err return err
} }
@ -176,7 +193,7 @@ func manipulate(dir *Dir) error {
// Manipulate pages // Manipulate pages
for i := range dir.Pages { for i := range dir.Pages {
var b bytes.Buffer var b bytes.Buffer
tmpl := templates[pageTmpl] tmpl := findTemplate(dir.Pages[i].Permalink, pageTmpl)
if err := tmpl.Execute(&b, dir.Pages[i]); err != nil { if err := tmpl.Execute(&b, dir.Pages[i]); err != nil {
return err return err
} }