Go pattern: cannot evaluate the field X in type Y (X is not part of Y, but loops in the loop {{range}})

A similar question was answered here , but I do not think it solves my problem.

Let's say you have the following structure:

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

In addition, the URL has the following structure: example.com/en/users, where "en" is the URL parameter that will be passed to the template as follows:

 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 since {{.lang}} is not part of the User structure, I get an error .. since I can access the {{.lang}} inside {{range.users}}

+5
source share
2 answers

The contents of the period ( . ) Are assigned to $ after calling range , so you can use $ to access lang ( in the game ):

 {{ 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 recorded here :

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

If you use nested ranges, you can always step back to assign a point to something else using the with statement or variable assignment operators. See another answer for this.

+7
source

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 in the documentation: https://golang.org/pkg/text/template/#hdr-Variables

+2
source

Source: https://habr.com/ru/post/1266435/


All Articles