Accessing Outer Scope Within a Templated "With" or "Range" Scope
In templates, employing "with" and "range" scopes temporarily alters the scope of the dot operator "." to refer to the inner scope's data. This can present a challenge when you wish to access data that resides in the calling scope.
Solution
To access the calling scope within a "with" or "range" scope, utilize the special variable "$". This variable represents the data value passed to the template, which is the original starting value for the "." dot operator.
For instance, in this template:
{{with .Inner}} Outer: {{$.OuterValue}} Inner: {{.InnerValue}} {{end}}
"$.OuterValue" refers to a variable in the outer (calling) scope, while ".InnerValue" pertains to a variable in the inner (local) scope established by "with .Inner".
Documentation
The documentation for text/template elucidates the purpose of "$":
"When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot."
The above is the detailed content of How to Access Outer Scope Variables from Within a Templated 'With' or 'Range' Scope?. For more information, please follow other related articles on the PHP Chinese website!