Go模板的range循环正在引用我的值。

huangapple go评论104阅读模式
英文:

Go templates range loop is quoting my value

问题

我有一个字符串切片(.Table.PKey.Columns),我想在模板中循环遍历它,生成一个执行一些追加操作的go文件。但是当我在模板中输出$value时,显然Go会为我加上引号,所以它给我报错:

5:27: 期望选择器或类型断言,找到'STRING' "ID"

也就是说,模板输出应该是类似于o.ID的样子,但实际上却变成了类似于o."ID"的样子(我猜测)。

我是否正确地认为这是使用range循环的结果?因为当我直接在其他地方访问变量时(例如,假设我有一个字符串并执行以下操作:o.{{.Table.MyString}}),它工作正常,但是一旦我尝试将range循环结合起来,它似乎就会加上引号。

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

有什么建议吗?谢谢。

英文:

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.

答案1

得分: 3

{{range}}不会对任何内容进行引用。如果在输出中看到"ID",那么你的输入值就是包含引号的"ID"

看看这个例子:

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

输出结果(在Go Playground上尝试):

Id1 Id1 "Id2" 
Id1
"Id2"
Abc
英文:

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

答案2

得分: 0

如果Go模板渲染的变量位于 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定