Go template: can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)
Asked Answered
V

2

32

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

Volvox answered 6/4, 2017 at 18:38 Comment(1)
You can declare vars in a Go template {{$lang := .lang}}{{range .users}} .... golang.org/pkg/text/template/#hdr-VariablesBriefcase
D
52

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.

Dayledaylight answered 6/4, 2017 at 18:42 Comment(2)
Your syntax is off, and also it doesn't really work that way, the context is still set to the whatever you're ranging over. play.golang.org/p/Qz63RBwdZhBriefcase
True. Fixing that.Dayledaylight
R
13

You can use a variable for .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 }}

See here at the documentation: https://golang.org/pkg/text/template/#hdr-Variables

Rubbery answered 6/4, 2017 at 18:43 Comment(1)
Thanks a lot, I can sadly just upvote since I accepted nemo's answer (since his was 1 minute faster and I ended up using it that way, although I'm sure in the future I'll want to do definitions like you showed, so wish I could accept both)Volvox

© 2022 - 2024 — McMap. All rights reserved.