Home  >  Article  >  Backend Development  >  How to Access Variables from Outer Ranges in Go Templates?

How to Access Variables from Outer Ranges in Go Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 03:36:02873browse

How to Access Variables from Outer Ranges in Go Templates?

Error: "Can't Evaluate Field X in Type Y" in Go Templates with Nested Ranges

The error "can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)" occurs when you attempt to access a field that is not a part of the struct being iterated over in a Go template. This can happen when you have nested ranges and attempt to access a variable that is defined in an outer range.

For instance, consider the following example:

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

func main() {
    users := []User{{"user1", []byte("password"), "user1@example.com"}, {"user2", []byte("password"), "user2@example.com"}}
    renderer.HTML(w, http.StatusOK, "users/index", map[string]interface{}{
        "lang":  "en",
        "users": users,
    })
}

In the corresponding template file, the following code attempts to access the lang variable within 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 }}

However, since lang is not a field of the User struct, the template engine will raise the error mentioned above. To resolve this issue, you can use the $ variable to access the current context, which contains all the variables defined in the outer range. The updated template code would look like this:

{{ 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 will correctly access the lang variable and generate the desired output.

The above is the detailed content of How to Access Variables from Outer Ranges in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn