0

I've got a slice of strings (.Table.PKey.Columns) that I'm trying to loop over in my template to generate a go file that does some appends, but when I output $value in my template, apparently Go is quoting it for me, so it is giving me the error:

5:27: expected selector or type assertion, found 'STRING' "ID"

i.e., instead of the template output looking something like o.ID -- which is what I'm aiming for, it ends up looking something like o."ID" (I presume).

Am I right in my assumption that this is the result of using a range loop? Because it seems when I access variables directly in other places (for example, say I had a string and I did: o.{{.Table.MyString}}) it works fine, but as soon as I try and incorporate a range loop into the mix it seems to be quoting things.

{{- range $key, $value := .Table.PKey.Columns }}
  args = append(args, o.{{$value}})
{{ end -}}

Any suggestions? Thank you.

b0xxed1n
  • 2,063
  • 5
  • 20
  • 30
  • 1
    Why did you say you presume? Have you seen the output (ie. before passing it to whatever gives the error you've quoted)? – djd Apr 23 '16 at 08:15
  • And are you using `text/template` or `html/template`? – djd Apr 23 '16 at 08:16
  • Yes, I've seen the output before passing it, there are no quotations in it. I'm using text/template – b0xxed1n Apr 23 '16 at 11:24

2 Answers2

3

The {{range}} does not quote anything. If you see "ID" in your output, then your input value is "ID" with quotation marks included!

See this example:

func main() {
    m := map[string]interface{}{
        "Id":     "Id1",
        "Quoted": `"Id2"`,
        "Ids":    []string{"Id1", `"Id2"`, "Abc"},
    }
    t := template.Must(template.New("").Parse(src))
    t.Execute(os.Stdout, m)
}

const src = `{{.Id}} {{index .Ids 0}} {{.Quoted}} 
{{range $key, $value := .Ids}}{{$value}}
{{end}}
`

Output (try it on the Go Playground):

Id1 Id1 "Id2" 
Id1
"Id2"
Abc
icza
  • 389,944
  • 63
  • 907
  • 827
0

If the variable Go Template is rendering is within tags, then Go Template will wrap any strings with quotes for you.

Some options include generating the in code prior to asking Go Template to render it.

Sienna
  • 1,570
  • 3
  • 24
  • 48
Tom
  • 1
  • 2