duanjuete9206 2017-04-06 18:38
浏览 19
已采纳

Go模板:无法评估类型Y的字段X(X不是Y的一部分,但停留在{{range}}循环中)

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

Let's say you have the following struct:

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

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

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

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

  • 写回答

2条回答 默认 最新

  • douxian9943 2017-04-06 18:42
    关注

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

    The behavior is documented here:

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)