英文:
How do I parse variables outside the range in Go templates?
问题
我有两个如下的结构体,并且我需要使用[templates][1]包在模板上渲染数据。我得到了以下错误信息:
<.Email>: Email is not a field of struct type Notes
.
问题似乎是只有范围结构体的字段在范围循环内可用,所以我想知道如何从范围结构体外部导入字段(例如Email字符串)。
这种行为相当出乎意料。
type notes struct{
Note string
sf string
}
type uis struct{
notes []Note
Email string
}
var ui uis
HTML
{{range .notes}}
{{.Email}} {{.sf}}
{{end}}
Email {{.Email}}
我已经查看了godocs,但它们似乎没有什么用处。
[1]: http://golang.org/pkg/text/template/
英文:
I have two structs as below and I need to render the data on a template using the [templates][1] pack. I get this error
<.Email>: Email is not a field of struct type Notes
.
The issue seems to be that only fields of the range struct seem to be available within the range loop so I'm wondering how I can import fields from outside the range struct (e.g. the Email string).
The behavior is quite unexpected.
type notes struct{
Note string
sf string
}
type uis struct{
notes []Note
Email string
}
var ui uis
HTML
{{range .notes}}
{{.Email}} {{.sf}}
{{end}}
Email {{.Email}}
I've checked the godocs but they seem quite useless.
[1]: http://golang.org/pkg/text/template/
答案1
得分: 37
从文档中可以得知:
当执行开始时,$ 被设置为传递给 Execute 的数据参数,也就是 dot 的初始值。
因此,你可以这样使用:
{{range .notes}}
{{$.Email}} {{.sf}}
{{end}}
Email {{.Email}}
(注意 range 内部的美元符号)
Playground 链接:http://play.golang.org/p/XiQFcGJEyR
附注:下次请尽量提供正确的代码和更好的解释。目前来看,我“认为”我已经回答了这个问题,但我不能确定。你的代码无法编译 - 例如,类型名称错误/与成员混合,并且你有未导出的字段,因此无法通过模板访问它们。
英文:
From the documentation:
> When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
Therefore, you can use this:
{{range .notes}}
{{$.Email}} {{.sf}}
{{end}}
Email {{.Email}}
(Note the dollar sign inside the range)
Playground link: http://play.golang.org/p/XiQFcGJEyR
Side note: Next time try to provide proper code and a better explanation. As it stands, I think I've answered this, but I cannot be sure. Your code doesn't compile - for example, type names are wrong/mixed with members and you have unexported fields so they cannot be accessed by the templates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论