Home > Backend Development > Golang > How can I access variables from the outer scope in nested 'with' or 'range' statements in Go templates?

How can I access variables from the outer scope in nested 'with' or 'range' statements in Go templates?

DDD
Release: 2024-11-24 10:57:10
Original
842 people have browsed it

How can I access variables from the outer scope in nested

Accessing Outer Scope in Nested "with" or "range" Scopes in Go Templates

In Go templates, the use of "with" or "range" statements creates a new scope, altering the context of the current scope. This can lead to situations where access to variables defined in the outer scope becomes necessary.

Using $. OuterValue

To retain access to the calling scope within a nested "with" or "range" scope, a specially defined variable called "$" is used. This variable is provided by the Go template engine and directs back to the data value that was passed to the Execute function, which represents the initial dot (.) value.

Example Usage

Consider the following template code:

{{with .Inner}}
  Outer: {{$.OuterValue}}
  Inner: {{.InnerValue}}
{{end}}
Copy after login

In this example, the "with" statement defines a new scope for the "Inner" variable. However, within this scope, accessing the "OuterValue" defined in the outer scope can be achieved using "$.OuterValue."

Documentation of $

The Go template documentation explicitly describes the role of "$" as follows:

"When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot."

This explanation confirms that "$" maintains the reference to the original data passed to the template, allowing access to the original scope's variables.

The above is the detailed content of How can I access variables from the outer scope in nested 'with' or 'range' statements in Go templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template