diff --git a/docs/templatefuncs.md b/docs/templatefuncs.md index d3abd1d..8bf448b 100644 --- a/docs/templatefuncs.md +++ b/docs/templatefuncs.md @@ -183,6 +183,16 @@ far adcda ``` +## `reverse` *list* + +`reverse` returns a copy of *list* in reverse order. + +```text +{{ list "a" "b" "c" }} + +[c b a] +``` + ## `stat` *path* `stat` returns a map representation of executing diff --git a/templatefuncs.go b/templatefuncs.go index be53de7..a2eec24 100644 --- a/templatefuncs.go +++ b/templatefuncs.go @@ -49,6 +49,7 @@ func NewFuncMap() template.FuncMap { "quote": eachString(strconv.Quote), "regexpReplaceAll": regexpReplaceAllTemplateFunc, "replaceAll": replaceAllTemplateFunc, + "reverse": reverseTemplateFunc, "stat": eachString(statTemplateFunc), "toJSON": toJSONTemplateFunc, "toLower": eachString(strings.ToLower), @@ -170,6 +171,14 @@ func regexpReplaceAllTemplateFunc(expr, repl, s string) string { return regexp.MustCompile(expr).ReplaceAllString(s, repl) } +// reverseTemplateFunc is the core implementation of the `reverse` +// template function. +func reverseTemplateFunc(list []any) []any { + listcopy := append([]any(nil), list...) + slices.Reverse(listcopy) + return listcopy +} + // statTemplateFunc is the core implementation of the `stat` template function. func statTemplateFunc(name string) any { switch fileInfo, err := os.Stat(name); { diff --git a/templatefuncs_test.go b/templatefuncs_test.go index ec544d9..39331fe 100644 --- a/templatefuncs_test.go +++ b/templatefuncs_test.go @@ -145,6 +145,10 @@ func TestFuncMap(t *testing.T) { template: `{{ quote "a" }}`, expected: `"a"`, }, + { + template: `{{ list "a" "b" "c" | reverse }}`, + expected: "[c b a]", + }, { template: `{{ (stat "testdata/file").type }}`, expected: "file",