Go 模板:无法评估类型 Y 中的字段 X(X 不是 Y 的一部分,但卡在 {{range}} 循环中)
Go template: can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)
,但我认为它没有解决我的问题。
假设您有以下结构:
type User struct {
Username string
Password []byte
Email string
...
}
此外,URL 具有如下结构:example.com/en/users
,其中 "en"
是一个 URL 参数,将像这样传递到模板中:
renderer.HTML(w, http.StatusOK, "users/index", map[string]interface{}{
"lang": chi.URLParam(r, "lang"),
"users": users})
在 HTML 模板中我有以下内容:
{{ range .users }}
<form action="/{{ .lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}
现在,问题是因为 {{ .lang }}
不是 User
结构的一部分,所以我得到了错误..所以我怎样才能在 [=18] 中访问 {{ .lang }}
=]?
调用range
后,点(.
)的内容赋值给$
,所以可以用$
访问lang
( on play):
{{ range .users }}
<form action="/{{ $.lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}
记录了行为 here:
When execution begins, $
is set to the data argument passed to Execute
, that is, to the starting value of dot.
如果您使用的是嵌套范围,您始终可以回退使用 with
语句或变量赋值语句将点分配给其他内容。请参阅 。
您可以为 .lang
使用变量
{{ $lang := .lang }}
{{ range .users }}
<form action="/{{ $lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}
假设您有以下结构:
type User struct {
Username string
Password []byte
Email string
...
}
此外,URL 具有如下结构:example.com/en/users
,其中 "en"
是一个 URL 参数,将像这样传递到模板中:
renderer.HTML(w, http.StatusOK, "users/index", map[string]interface{}{
"lang": chi.URLParam(r, "lang"),
"users": users})
在 HTML 模板中我有以下内容:
{{ range .users }}
<form action="/{{ .lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}
现在,问题是因为 {{ .lang }}
不是 User
结构的一部分,所以我得到了错误..所以我怎样才能在 [=18] 中访问 {{ .lang }}
=]?
调用range
后,点(.
)的内容赋值给$
,所以可以用$
访问lang
( on play):
{{ range .users }}
<form action="/{{ $.lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}
记录了行为 here:
When execution begins,
$
is set to the data argument passed toExecute
, that is, to the starting value of dot.
如果您使用的是嵌套范围,您始终可以回退使用 with
语句或变量赋值语句将点分配给其他内容。请参阅
您可以为 .lang
{{ $lang := .lang }}
{{ range .users }}
<form action="/{{ $lang }}/users" method="POST">
<input type="text" name="Username" value="{{ .Username }}">
<input type="text" name="Email" value="{{ .Email }}">
</form>
{{ end }}