Home >Backend Development >Golang >How to Access External Parameters in a Go Template Range Loop?

How to Access External Parameters in a Go Template Range Loop?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 15:42:02374browse

How to Access External Parameters in a Go Template Range Loop?

Go Template Accessing External Parameter in a Range Loop

Consider a situation where you have a User struct with fields like Username, Password, and Email. In a web application, the URL structure may include a language parameter (en) that needs to be accessed within a template that iterates over users.

In the provided template:

{{ range .users }}
  <form action="/{{ .lang }}/users" method="POST">
    <input type="text" name="Username" value="{{ .Username }}">
    <input type="text" name="Email" value="{{ .Email }}">
  </form>
{{ end }}

Accessing .lang within the range loop results in the following error:

"can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)"

To solve this issue, it's necessary to access the .lang parameter from outside the loop. This can be achieved by using the $ variable. After the range invocation, the contents of the range variable (. in this case) are assigned to $. Therefore, the template can be modified as follows:

{{ range .users }}
  <form action="/{{ $.lang }}/users" method="POST">
    <input type="text" name="Username" value="{{ .Username }}">
    <input type="text" name="Email" value="{{ .Email }}">
  </form>
{{ end }}

By using $, the template can successfully access the .lang parameter despite it not being a field in the User struct.

The above is the detailed content of How to Access External Parameters in a Go Template Range Loop?. 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