"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to access external parameters in Go template scope loop?

How to access external parameters in Go template scope loop?

Posted on 2025-04-14
Browse:190

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 }}
  
{{ 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 }}
  
{{ end }}

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3