首頁  >  文章  >  後端開發  >  如何在「with」或「range」作用域內存取 Go 範本中的外部作用域變數?

如何在「with」或「range」作用域內存取 Go 範本中的外部作用域變數?

DDD
DDD原創
2024-11-13 15:52:03629瀏覽

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.

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn