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 have a 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 }}?
The contents of dot (
.
) are assigned to$
after invocation ofrange
, so you can use$
to accesslang
(on play):The behavior is documented here:
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
See here at the documentation: https://golang.org/pkg/text/template/#hdr-Variables