Skip to content

Commit

Permalink
Merge pull request #98 from skx/97-env
Browse files Browse the repository at this point in the history
Allow environmental variable lookup in our templates.
  • Loading branch information
skx authored May 4, 2022
2 parents 915df4f + 21dbf9a commit db234c3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
13 changes: 13 additions & 0 deletions processor/emailer/emailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"os/exec"
"path/filepath"
"strconv"
"strings"
"text/template"

"github.com/mmcdole/gofeed"
Expand Down Expand Up @@ -51,6 +52,16 @@ func New(feed *gofeed.Feed, item withstate.FeedItem, opts []configfile.Option) *
return &Emailer{feed: feed, item: item, opts: opts}
}

// env returns the contents of an environmental variable.
func env(s string) string {
return (os.Getenv(s))
}

// split converts a string to an array.
func split(in string, delim string) []string {
return strings.Split(in, delim)
}

// loadTemplate loads the template used for sending the email notification.
func (e *Emailer) loadTemplate() (*template.Template, error) {

Expand Down Expand Up @@ -83,7 +94,9 @@ func (e *Emailer) loadTemplate() (*template.Template, error) {
// Function map allows exporting functions to the template
//
funcMap := template.FuncMap{
"env": env,
"quoteprintable": e.toQuotedPrintable,
"split": split,
}

tmpl := template.Must(template.New("email.tmpl").Funcs(funcMap).Parse(string(content)))
Expand Down
6 changes: 4 additions & 2 deletions template/template.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
case you need access to other fields which are not exported expliclty.
Using that approach you can access {{.RSSItem.GUID}}, for example.

Functions:
The following functions are also available:

{{quoteprintable .Link}} -> Quote the specified field.
{{env "USER"}} -> Return the given environmental variable
{{quoteprintable .Link}} -> Quote the specified field.
{{split "STRING:HERE" ":"}} -> Split a string into an array by deliminator

This comment will be stripped from the generated email.

Expand Down
11 changes: 9 additions & 2 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,15 @@ package template
import "testing"

func TestTemplate(t *testing.T) {

// content of our template
content := EmailTemplate()
if len(content) != 2265 {
t.Fatalf("unexpected template size 2265 != %d", len(content))

// expected template length
length := 2457

// check the content is as big as it should be.
if len(content) != length {
t.Fatalf("unexpected template size %d != %d", length, len(content))
}
}

0 comments on commit db234c3

Please sign in to comment.