Skip to content

Commit

Permalink
Add duration function to templates
Browse files Browse the repository at this point in the history
Signed-off-by: Vadim Aleksandrov <valeksandrov@me.com>
  • Loading branch information
verdel committed Apr 22, 2024
1 parent dc1e1a2 commit 740a580
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,4 @@ templating.
| stringSlice | ...string | Returns the passed strings as a slice of strings. |
| date | string, time.Time | Returns the text representation of the time in the specified format. For documentation on formats refer to [pkg.go.dev/time](https://pkg.go.dev/time#pkg-constants). |
| tz | string, time.Time | Returns the time in the timezone. For example, Europe/Paris. |
| duration | string | Returns the time.Duration representation of a passed string. |
4 changes: 4 additions & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ var DefaultFuncs = FuncMap{
}
return t.In(loc), nil
},
// duration returns the time.Duration representation of a passed string
"duration": func(text string) (time.Duration, error) {
return time.ParseDuration(text)
},
}

// Pair is a key/value string pair.
Expand Down
8 changes: 8 additions & 0 deletions template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,14 @@ func TestTemplateFuncs(t *testing.T) {
in: `{{ . | tz "Invalid/Timezone" }}`,
data: time.Date(2024, 1, 1, 8, 15, 30, 0, time.UTC),
expErr: "template: :1:7: executing \"\" at <tz \"Invalid/Timezone\">: error calling tz: unknown time zone Invalid/Timezone",
}, {
title: "Template using duration",
in: `{{ "60s" | duration | printf "%d" }}`,
exp: "60000000000",
}, {
title: "Template using invalid duration",
in: `{{ "60k" | duration | printf "%d" }}`,
expErr: "template: :1:11: executing \"\" at <duration>: error calling duration: time: unknown unit \"k\" in duration \"60k\"",
}} {
tc := tc
t.Run(tc.title, func(t *testing.T) {
Expand Down

0 comments on commit 740a580

Please sign in to comment.