From bdba6384dc1a63fb384a658ca330372a8e96aa4b Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Tue, 5 Mar 2024 02:52:01 +0100 Subject: [PATCH] feat: Add replaceAll function --- docs/templatefuncs.md | 10 ++++++++++ templatefuncs.go | 8 ++++++++ templatefuncs_test.go | 8 ++++++++ 3 files changed, 26 insertions(+) diff --git a/docs/templatefuncs.md b/docs/templatefuncs.md index 0a41b79..4d9a362 100644 --- a/docs/templatefuncs.md +++ b/docs/templatefuncs.md @@ -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 diff --git a/templatefuncs.go b/templatefuncs.go index 812fb1e..de03047 100644 --- a/templatefuncs.go +++ b/templatefuncs.go @@ -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), @@ -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 { //nolint: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 { diff --git a/templatefuncs_test.go b/templatefuncs_test.go index 72029dd..5a13fa6 100644 --- a/templatefuncs_test.go +++ b/templatefuncs_test.go @@ -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"`,