From f054cdf391ccf6801851dd82f47d0d419a7b6b38 Mon Sep 17 00:00:00 2001 From: adnano Date: Wed, 21 Apr 2021 14:39:13 -0400 Subject: [PATCH] Make templates optional --- dir.go | 35 ++++++++++++++++++++++------------- templates.go | 13 ++++++------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/dir.go b/dir.go index 6bfa7dc..b622819 100644 --- a/dir.go +++ b/dir.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "fmt" "io" "io/ioutil" "log" @@ -89,22 +90,26 @@ func (d *Dir) Process(cfg *Config, task *Task) error { if task.TemplateExt != "" { // Create index if d.index != nil { - var b strings.Builder - tmpl := cfg.Templates.FindTemplate(d.Path, "index"+task.TemplateExt) - if err := tmpl.Execute(&b, d); err != nil { - return err + tmpl, ok := cfg.Templates.FindTemplate(d.Path, "index"+task.TemplateExt) + if ok { + var b strings.Builder + if err := tmpl.Execute(&b, d); err != nil { + return err + } + d.index.Content = b.String() } - 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) - if err := tmpl.Execute(&b, d.Pages[i]); err != nil { - return err + 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() } - d.Pages[i].Content = b.String() } } @@ -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") - if err := tmpl.Execute(&b, feed); err != nil { - return err + 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) } - d.feed = b.Bytes() } // Process subdirectories diff --git a/templates.go b/templates.go index 1423e3a..ec031be 100644 --- a/templates.go +++ b/templates.go @@ -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 }