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.
以上是如何在「with」或「range」作用域內存取 Go 範本中的外部作用域變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!