template: add the default template function stringSlice (#2101)

Since it's impossible to create a string slice in a Go template by
default, add a function to work around this problem.

The use case is to make it easy to call KV.Remove with an arbitrary
slice inside a template.

Signed-off-by: Vincent Rischmann <vincent@rischmann.fr>
This commit is contained in:
Vincent Rischmann 2019-11-13 10:32:51 +01:00 committed by Brian Brazil
parent 64acc9bdf9
commit 66a0ed21bd
2 changed files with 16 additions and 0 deletions

View File

@ -141,6 +141,9 @@ var DefaultFuncs = FuncMap{
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, repl)
},
"stringSlice": func(s ...string) []string {
return s
},
}
// Pair is a key/value string pair.

View File

@ -357,6 +357,19 @@ func TestTemplateExpansion(t *testing.T) {
in: `{{ reReplaceAll "ab" "AB" "abcdabcda"}}`,
exp: "ABcdABcda",
},
{
title: "Template using stringSlice",
in: `{{ with .GroupLabels }}{{ with .Remove (stringSlice "key1" "key3") }}{{ .SortedPairs.Values }}{{ end }}{{ end }}`,
data: Data{
GroupLabels: KV{
"key1": "key1",
"key2": "key2",
"key3": "key3",
"key4": "key4",
},
},
exp: "[key2 key4]",
},
} {
tc := tc
t.Run(tc.title, func(t *testing.T) {