Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

templates

go

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.

like image 779
Taoist Avatar asked Oct 26 '25 05:10

Taoist


1 Answers

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

like image 162
Jasmine Crockett Avatar answered Oct 28 '25 02:10

Jasmine Crockett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!