diff options
author | Robin Jarry <robin@jarry.cc> | 2023-06-08 22:16:31 +0200 |
---|---|---|
committer | Robin Jarry <robin@jarry.cc> | 2023-06-10 23:54:06 +0200 |
commit | 9479513ec138b0e4b2ad2c53a0566c00c7035845 (patch) | |
tree | 98ce844e82eeebf2151a3c0fa1ac1b530964f344 /lib/templates/functions.go | |
parent | 8162c5be8f251e985a18928ed1a8cb571df40945 (diff) | |
download | aerc-9479513ec138b0e4b2ad2c53a0566c00c7035845.tar.gz |
templates: add map functions
Similar to switch and .StyleSwitch, add map and .StyleMap to work on
lists. An extra "exclude" item is available to filter elements out of
the list.
Signed-off-by: Robin Jarry <robin@jarry.cc>
Tested-by: Inwit <inwit@sindominio.net>
Diffstat (limited to 'lib/templates/functions.go')
-rw-r--r-- | lib/templates/functions.go | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/lib/templates/functions.go b/lib/templates/functions.go index b331dc85..9380bc7b 100644 --- a/lib/templates/functions.go +++ b/lib/templates/functions.go @@ -255,12 +255,18 @@ func compactDir(path string) string { type ( Case struct{ expr, value string } Default struct{ value string } + Exclude struct{ expr string } ) func (c *Case) Matches(s string) bool { return parse.MatchCache(s, c.expr) } func (c *Case) Value() string { return c.value } +func (c *Case) Skip() bool { return false } func (d *Default) Matches(s string) bool { return true } func (d *Default) Value() string { return d.value } +func (d *Default) Skip() bool { return false } +func (e *Exclude) Matches(s string) bool { return parse.MatchCache(s, e.expr) } +func (e *Exclude) Value() string { return "" } +func (e *Exclude) Skip() bool { return true } func switch_(value string, cases ...models.Case) string { for _, c := range cases { @@ -279,6 +285,28 @@ func default_(value string) models.Case { return &Default{value: value} } +func exclude(expr string) models.Case { + return &Exclude{expr: expr} +} + +func map_(elements []string, cases ...models.Case) []string { + mapped := make([]string, 0, len(elements)) +top: + for _, e := range elements { + for _, c := range cases { + if c.Matches(e) { + if c.Skip() { + continue top + } + e = c.Value() + break + } + } + mapped = append(mapped, e) + } + return mapped +} + var templateFuncs = template.FuncMap{ "quote": quote, "wrapText": wrapText, @@ -304,4 +332,6 @@ var templateFuncs = template.FuncMap{ "switch": switch_, "case": case_, "default": default_, + "map": map_, + "exclude": exclude, } |