Home >Backend Development >Golang >How to Access Outer Scope Variables in Go Templates Within 'with' or 'range' Scopes?

How to Access Outer Scope Variables in Go Templates Within 'with' or 'range' Scopes?

DDD
DDDOriginal
2024-11-13 15:52:03743browse

How to Access Outer Scope Variables in Go Templates Within

Accessing Outer Scope in a Template Within "with" or "range" Scopes

When using the "with" or "range" scopes within a Go template, the scope of the dot (.) operator changes to the current loop variable or struct member. This can make it challenging to access variables or functions defined in the outer scope.

To address this issue, Go templates provide a special variable named "$" that provides access to the outer scope. Here's how to use it:

{{with .Inner}}
  Outer: {{$.OuterValue}}  # Accesses the OuterValue variable from the outer scope
  Inner: {{.InnerValue}}  # Accesses the InnerValue variable from the inner scope
{{end}}

The "$" variable is documented in the text/template documentation:

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

This means that "$" always points to the original data object passed to the template, allowing you to access variables and functions defined in the outer scope.

The above is the detailed content of How to Access Outer Scope Variables in Go Templates Within 'with' or 'range' Scopes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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