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}}
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!