Skip to content

Commit

Permalink
feat: Add replaceAll function
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed May 18, 2024
1 parent 9907d6a commit 6d3a0e9
Show file tree
Hide file tree
Showing 3 changed files with 26 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 @@ -142,6 +142,16 @@ with *replacement* in *string*.
far
```

## `replaceAll` *old* *new* *string*

`replaceAll` replaces all instances of *old* with *new* in *string*.

```text
{{ "abcba" | replaceAll "b" "d" }}
adcda
```

## `stat` *path*

`stat` returns a map representation of executing
Expand Down
8 changes: 8 additions & 0 deletions templatefuncs.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func NewFuncMap() template.FuncMap {
"prefixLines": prefixLinesTemplateFunc,
"quote": eachString(strconv.Quote),
"regexpReplaceAll": regexpReplaceAllTemplateFunc,
"replaceAll": replaceAllTemplateFunc,
"stat": eachString(statTemplateFunc),
"toJSON": toJSONTemplateFunc,
"toLower": eachString(strings.ToLower),
Expand Down Expand Up @@ -145,6 +146,13 @@ func prefixLinesTemplateFunc(prefix, s string) string {
return builder.String()
}

// replaceAllTemplateFunc is the `replaceAll` template function.
func replaceAllTemplateFunc(old, new string, v any) any {

Check failure on line 150 in templatefuncs.go

View workflow job for this annotation

GitHub Actions / lint

param new has same name as predeclared identifier (predeclared)
return eachString(func(s string) any {
return strings.ReplaceAll(s, old, new)
})(v)
}

// regexpReplaceAllTemplateFunc is the core implementation of the
// `regexpReplaceAll` template function.
func regexpReplaceAllTemplateFunc(expr, repl, s string) string {
Expand Down
8 changes: 8 additions & 0 deletions templatefuncs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ func TestFuncMap(t *testing.T) {
"# b",
),
},
{
template: `{{ "abcba" | replaceAll "b" "d" }}`,
expected: `adcda`,
},
{
template: `{{ list "abc" "cba" | replaceAll "b" "d" }}`,
expected: "[adc cda]",
},
{
template: `{{ quote "a" }}`,
expected: `"a"`,
Expand Down

0 comments on commit 6d3a0e9

Please sign in to comment.