Make templates optional

This commit is contained in:
adnano 2021-04-21 14:39:13 -04:00
parent 27684b26f3
commit f054cdf391
2 changed files with 28 additions and 20 deletions

15
dir.go
View file

@ -2,6 +2,7 @@ package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
@ -89,24 +90,28 @@ func (d *Dir) Process(cfg *Config, task *Task) error {
if task.TemplateExt != "" {
// Create index
if d.index != nil {
tmpl, ok := cfg.Templates.FindTemplate(d.Path, "index"+task.TemplateExt)
if ok {
var b strings.Builder
tmpl := cfg.Templates.FindTemplate(d.Path, "index"+task.TemplateExt)
if err := tmpl.Execute(&b, d); err != nil {
return err
}
d.index.Content = b.String()
}
}
// Process pages
for i := range d.Pages {
var b strings.Builder
tmpl := cfg.Templates.FindTemplate(d.Path, "page"+task.TemplateExt)
tmpl, ok := cfg.Templates.FindTemplate(d.Path, "page"+task.TemplateExt)
if ok {
if err := tmpl.Execute(&b, d.Pages[i]); err != nil {
return err
}
d.Pages[i].Content = b.String()
}
}
}
// Feed represents a feed.
type Feed struct {
@ -125,11 +130,15 @@ func (d *Dir) Process(cfg *Config, task *Task) error {
Updated: time.Now(),
Entries: d.Pages,
}
tmpl := cfg.Templates.FindTemplate(d.Path, "atom.xml")
tmpl, ok := cfg.Templates.FindTemplate(d.Path, "atom.xml")
if ok {
if err := tmpl.Execute(&b, feed); err != nil {
return err
}
d.feed = b.Bytes()
} else {
fmt.Printf("Warning: failed to generate feed %q: missing template \"atom.xml\"\n", title)
}
}
// Process subdirectories

View file

@ -2,7 +2,6 @@ package main
import (
"io/ioutil"
"log"
"os"
pathpkg "path"
"path/filepath"
@ -56,15 +55,15 @@ func (t *Templates) Load(dir string) error {
})
}
// 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 {
// FindTemplate returns the template for the given path.
func (t *Templates) FindTemplate(path string, tmpl string) (*template.Template, bool) {
tmplPath := pathpkg.Join(path, tmpl)
if t, ok := t.tmpls[tmplPath]; ok {
return t
return t, true
}
if t, ok := t.tmpls[pathpkg.Join("/_default", tmpl)]; ok {
return t
return t, true
}
log.Fatalf("failed to find template %q", tmpl)
return nil
// Failed to find template
return nil, false
}