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