Home > Article > Backend Development > How to Access Non-Struct Fields in Go Templates Within Range Loops?
Accessing Non-Struct Fields in Go Templates Within Range Loops
When iterating over a slice of structs within a Go template using the {{range}} loop, you may encounter an error if you attempt to access a field that is not directly part of the struct. For instance, consider the following example:
type User struct { Username string Password []byte Email string ... } renderer.HTML(w, http.StatusOK, "users/index", map[string]interface{}{ "lang": chi.URLParam(r, "lang"), "users": users})
Within the HTML template, you might encounter the following error when trying to access the {{ .lang }} field:
`got template: can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)`
This error occurs because the {{ .lang }} field is not part of the User struct. To resolve this issue, you can utilize the $ variable, which references the data assigned to {{ . }} following the invocation of the {{range}} loop.
{{ range .users }} <form action="/{{ $.lang }}/users" method="POST"> <input type="text" name="Username" value="{{ .Username }}"> <input type="text" name="Email" value="{{ .Email }}"> </form> {{ end }}
As per the Go template documentation, when the {{range}} loop begins execution, the $ variable is automatically set to the data argument passed to the template. In this case, the data argument is a map that includes the lang key. Therefore, you can use $ to access the lang value within the loop.
If you require access to multiple non-struct fields within nested loops, you can also utilize the with statement or variable assignment statements to assign {{ . }} to a different variable.
The above is the detailed content of How to Access Non-Struct Fields in Go Templates Within Range Loops?. For more information, please follow other related articles on the PHP Chinese website!