30

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

gmds
  • 19,325
  • 4
  • 32
  • 58
fisker
  • 979
  • 4
  • 18
  • 28
  • 1
    You can declare vars in a Go template `{{$lang := .lang}}{{range .users}} ...`. https://golang.org/pkg/text/template/#hdr-Variables – mkopriva Apr 06 '17 at 18:41

2 Answers2

50

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.

Community
  • 1
  • 1
nemo
  • 55,207
  • 13
  • 135
  • 135
11

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

apxp
  • 5,240
  • 4
  • 23
  • 43
  • 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) – fisker Apr 06 '17 at 19:05