diff options
author | René 'Necoro' Neumann <necoro@necoro.eu> | 2022-01-09 01:20:34 +0100 |
---|---|---|
committer | René 'Necoro' Neumann <necoro@necoro.eu> | 2022-01-09 13:18:32 +0100 |
commit | 0384d631d2edb8383d0840940be066d96a5badc7 (patch) | |
tree | 71cac6f7f309794b4a72e88afa1c3aedcc6bd6b2 /internal/feed/template/template.go | |
parent | 914be83c6066ffb8103707528f8e8279df97bf63 (diff) | |
download | feed2imap-go-0384d631d2edb8383d0840940be066d96a5badc7.tar.gz feed2imap-go-0384d631d2edb8383d0840940be066d96a5badc7.tar.bz2 feed2imap-go-0384d631d2edb8383d0840940be066d96a5badc7.zip |
#66: Support for specifying custom templates
Diffstat (limited to '')
-rw-r--r-- | internal/feed/template/template.go | 42 |
1 files changed, 36 insertions, 6 deletions
diff --git a/internal/feed/template/template.go b/internal/feed/template/template.go index 8b3fb73..d66a8e4 100644 --- a/internal/feed/template/template.go +++ b/internal/feed/template/template.go @@ -2,13 +2,20 @@ package template import ( _ "embed" + "errors" + "fmt" html "html/template" "io" + "io/fs" + "os" text "text/template" + + "github.com/Necoro/feed2imap-go/pkg/log" ) type template interface { Execute(wr io.Writer, data interface{}) error + Name() string } type Template struct { @@ -24,21 +31,44 @@ var defaultHtmlTpl string var defaultTextTpl string var Html = Template{ - useHtml: true, - dflt: defaultHtmlTpl, + useHtml: true, + dflt: defaultHtmlTpl, + template: html.New("Html").Funcs(funcMap), } var Text = Template{ - useHtml: false, - dflt: defaultTextTpl, + useHtml: false, + dflt: defaultTextTpl, + template: text.New("Text").Funcs(funcMap), } func (tpl *Template) loadDefault() { + if err := tpl.load(tpl.dflt); err != nil { + panic(err) + } +} + +func (tpl *Template) load(content string) (err error) { if tpl.useHtml { - tpl.template = html.Must(html.New("Html").Funcs(funcMap).Parse(tpl.dflt)) + _, err = tpl.template.(*html.Template).Parse(content) } else { - tpl.template = text.Must(text.New("Text").Funcs(funcMap).Parse(tpl.dflt)) + _, err = tpl.template.(*text.Template).Parse(content) } + return +} + +func (tpl *Template) LoadFile(file string) error { + content, err := os.ReadFile(file) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + log.Errorf("Template file '%s' does not exist, keeping default.", file) + return nil + } else { + return fmt.Errorf("reading template file '%s': %w", file, err) + } + } + + return tpl.load(string(content)) } func init() { |