This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Cyber
Have you ever wanted to pass multiple arguments to a go template? If you google it you'll be convinced it's not possible. But bear with me.
In go templates you can pass a single "argument" (pipeline in go parlance) to a template defined block. But by creating a simple helper function you can pass as many arguments as you want. Simply add this function to your FuncMap
:
func(els ...any) []any {
return els
}
And you'll be able to create constructs such as:
{{ template "MyTemplate" (arr "str" 123 .Some.Value) }}
{{ define "MyTeplate" }}
{{ $strArg := index . 0 }}
{{ $intArg := index . 1 }}
{{ $valArg := index . 2 }}
This is my str {{ $strArg }} parameter.
...
{{ end }}
I named arr
my helper func, but you can call it whatever you want.
Enjoy!
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Cyber
Cyber | Sciencx (2022-11-28T21:04:31+00:00) Passing multiple arguments to golang templates. Retrieved from https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.