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 6241cb0 commit db09d3c
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 @@ -173,6 +173,16 @@ with *replacement* in *string*.
far
```

## `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 @@ -48,6 +48,7 @@ func NewFuncMap() template.FuncMap {
"prefixLines": prefixLinesTemplateFunc,
"quote": eachString(strconv.Quote),
"regexpReplaceAll": regexpReplaceAllTemplateFunc,
"reverse": reverseTemplateFunc,
"stat": eachString(statTemplateFunc),
"toJSON": toJSONTemplateFunc,
"toLower": eachString(strings.ToLower),
Expand Down Expand Up @@ -162,6 +163,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 @@ -137,6 +137,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 db09d3c

Please sign in to comment.