I have a custom function using Go templates as follows:
"listOperate": func(lst []string, fn func(string) string) (result []string) {
result = make([]string, len(lst))
for i, item := range lst {
result[i] = fn(item)
}
return result
},
I have another function which operates on a string:
"toCamel": func(str string) (result string) {
return strcase.ToCamel(str)
}
How can I call the first function, using the second as a parameter?
Copilot gives me the following
{{ listOperate . toCamel}}
which makes sense but fails to parse with the error
at <toCamel>: wrong number of args for toCamel: want 1 got 0" (template.ExecError)
which suggests it is trying to execute the function instead of passing it. Google gives me plenty of information on custom functions but nothing answers this problem.
I have a custom function using Go templates as follows:
"listOperate": func(lst []string, fn func(string) string) (result []string) {
result = make([]string, len(lst))
for i, item := range lst {
result[i] = fn(item)
}
return result
},
I have another function which operates on a string:
"toCamel": func(str string) (result string) {
return strcase.ToCamel(str)
}
How can I call the first function, using the second as a parameter?
Copilot gives me the following
{{ listOperate . toCamel}}
which makes sense but fails to parse with the error
at <toCamel>: wrong number of args for toCamel: want 1 got 0" (template.ExecError)
which suggests it is trying to execute the function instead of passing it. Google gives me plenty of information on custom functions but nothing answers this problem.
Share Improve this question edited Mar 5 at 17:29 Mr_Pink 110k17 gold badges283 silver badges272 bronze badges asked Mar 5 at 15:43 TaoistTaoist 3831 gold badge4 silver badges11 bronze badges1 Answer
Reset to default 6There is not a way to name a function without calling the function. The code {{ listOperate . toCamel}}
calls toCamel
with no arguments.
Write a template function that returns the function:
"toCamelFunc": func() any {
return func(str string) (result string) {
return strcase.ToCamel(str)
}
}
Use it like this: {{ listOperate . toCamelFunc}}