Home > Backend Development > Golang > How to Access Outer Scope Variables from Within a Templated 'With' or 'Range' Scope?

How to Access Outer Scope Variables from Within a Templated 'With' or 'Range' Scope?

Patricia Arquette
Release: 2024-11-11 18:49:03
Original
751 people have browsed it

How to Access Outer Scope Variables from Within a Templated

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}}
Copy after login

"$.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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template