Go template: can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)
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 toExecute
, 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.
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