Skip to content

Commit

Permalink
reverse
Browse files Browse the repository at this point in the history
  • Loading branch information
bradenhilton committed May 18, 2024
1 parent bf5e4c5 commit 3fd6298
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/templatefuncs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions templatefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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); {
Expand Down
4 changes: 4 additions & 0 deletions templatefuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 3fd6298

Please sign in to comment.