6

Is there any way to "spread" parameters in Go templates?

In my code I have a function that returns the properties of a list of structs as a string slice

"colStr": func(col string, a ...interface{}) []string {
    s := make([]string, len(a))
    for i, v := range a {
        if structs.IsStruct(v) {
            s[i] = db.Str(structs.Map(v)[col])
        }
    }
    return s
},

But how do I pass to this function? In the template itself, I have something that looks like this

{{list (colStr `Number` .QuoteProofs...) `&`}}{{end}}

But that gives me

template: HTML:17: unexpected <.> in operand

Is there any way to do this with templates?

Brian Leishman
  • 8,155
  • 11
  • 57
  • 93
  • 4
    Explosion is not supported in templates. You can define a second function that takes a slice and calls your other function exploding the slice (or vice versa). – Adrian Feb 14 '19 at 19:23
  • I see, yeah I was hoping to find a generic way that wouldn't depend on my types, but if it doesn't exist, then I'll have to go the method route – Brian Leishman Feb 14 '19 at 19:25
  • 1
    Or if this is how you wish to call `colStr` (by passing an exploded slice), you shouldn't declare it to have variadic parameter in the first place, so you don't have any problem. If you do need it to be variadic, another Go function that does the explosion as mentioned by @Adrian is the solution. – icza Feb 14 '19 at 21:20

0 Answers0