gotemplates

How do I pass a function as a parameter to another function in Go templates


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.


Solution

  • There 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}}