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)

查看:106
本文介绍了Go模板:无法评估类型Y的字段X(X不是Y的一部分,但停留在{{range}}循环中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处回答类似问题,但我认为这不能解决我的问题.

Similar question answered here, but I don't think it solves my problem.

假设您具有以下结构:

type User struct {
    Username string
    Password []byte
    Email string
    ...
}

此外,URL具有这样的结构:example.com/en/users,其中"en"是将被传递到模板中的URL参数,如下所示:

Moreover, the URL hasa structure like this: example.com/en/users, where "en" is a URL param that will be passed into the template like this:

renderer.HTML(w, http.StatusOK, "users/index", map[string]interface{}{
  "lang":  chi.URLParam(r, "lang"),
  "users": users})

在HTML模板中,我有以下内容:

And in the HTML template I have the following:

{{ 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结构的一部分,所以我得到了错误..那么如何在{{ range .users }}内部访问{{ .lang }}?

Now, the problem is that because {{ .lang }} is not a part of the User struct then I get the error.. so how can I access {{ .lang }} inside {{ range .users }}?

推荐答案

点(.)的内容在调用range后分配给$,因此您可以使用$访问(播放中):

The contents of dot (.) are assigned to $ after invocation of range, so you can use $ to access 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 }}

此处:

执行开始时,将$设置为传递给Execute的数据参数,即dot的起始值.

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

如果使用的是嵌套范围,则始终可以使用with语句或变量赋值语句回退以将点分配给其他对象.参见其他答案.

If you are using nested ranges, you can always fall back to assign dot to something else using the with statement or variable assignment statements. See the other answer for that.

这篇关于Go模板:无法评估类型Y的字段X(X不是Y的一部分,但停留在{{range}}循环中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆