Home > Article > Backend Development > How to Access Non-Struct Fields in Go Template Range Loops?
In Go HTML templates, accessing fields that are not part of the iterated struct in a range loop can cause the "can't evaluate field X in type Y" error.
To solve this issue, let's examine a scenario where a User struct lacks the .lang field but the template needs to access it.
Sample User Struct:
type User struct { Username string Password []byte Email string ... }
URL Structure:
example.com/en/users
Template Code:
{{ range .users }} <form action="/{{ .lang }}/users" method="POST"> <input type="text" name="Username" value="{{ .Username }}"> <input type="text" name="Email" value="{{ .Email }}"> </form> {{ end }}
Error:
"can't evaluate field lang in type User"
Solution:
To access .lang from within the loop, you can use the $ variable, which is assigned the value of dot (.) after execution of range.
{{ range .users }} <form action="/{{ $.lang }}/users" method="POST"> <input type="text" name="Username" value="{{ .Username }}"> <input type="text" name="Email" value="{{ .Email }}"> </form> {{ end }}
This is because according to the Go template documentation, "$ is set to the data argument passed to Execute, that is, to the starting value of dot."
Therefore, the $ variable can be used to access fields that are not part of the struct being iterated over within a range loop.
The above is the detailed content of How to Access Non-Struct Fields in Go Template Range Loops?. For more information, please follow other related articles on the PHP Chinese website!