Passing multiple arguments to golang templates

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 …


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Passing multiple arguments to golang templates." Cyber | Sciencx - Monday November 28, 2022, https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/
HARVARD
Cyber | Sciencx Monday November 28, 2022 » Passing multiple arguments to golang templates., viewed ,<https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/>
VANCOUVER
Cyber | Sciencx - » Passing multiple arguments to golang templates. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/
CHICAGO
" » Passing multiple arguments to golang templates." Cyber | Sciencx - Accessed . https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/
IEEE
" » Passing multiple arguments to golang templates." Cyber | Sciencx [Online]. Available: https://www.scien.cx/2022/11/28/passing-multiple-arguments-to-golang-templates/. [Accessed: ]
rf:citation
» Passing multiple arguments to golang templates | Cyber | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.