How Do I Access Variables from the Outer Scope within 'with' or 'range' Blocks in Go Templates?

Barbara Streisand
Release: 2024-11-19 07:51:02
Original
680 people have browsed it

How Do I Access Variables from the Outer Scope within

Accessing Outer Scope within "with" or "range" Scopes in Templates

Within the limited scope of "with" or "range" blocks, the scope of the "dot" (.) reference is restricted to the current block. However, there may arise scenarios where you need to access variables or data from the calling scope. This guide will explain how to navigate this scenario using the "$" reference.

When executing a template, the "$" reference is set to the data argument passed to Execute, which represents the starting value of "dot" (.). Therefore, to access variables outside the "with" or "range" block, you can utilize "$" as a reference to the enclosing scope's data.

For example, consider the following code snippet:

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

In this case, the "$" reference is used within the "with" block to access the "OuterValue" variable from the enclosing scope. This allows you to reference both the outer and inner scope variables within the same code block.

The "$" reference is a versatile tool for managing scope in Go templates. It allows you to seamlessly access variables and data from different levels of nesting and provides flexibility in your template designs.

The above is the detailed content of How Do I Access Variables from the Outer Scope within 'with' or 'range' Blocks 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template