首頁 > 後端開發 > Golang > 主體

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

DDD
發布: 2024-11-13 15:52:03
原創
633 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板