Go templates range loop is quoting my value


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.


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

Output (try it on the Go Playground):

Id1 Id1 "Id2" 

Answered By – icza

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.