首頁 >後端開發 >Golang >如何在 Go 中存取嵌套模板內的外部作用域?

如何在 Go 中存取嵌套模板內的外部作用域?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-11-15 11:38:02744瀏覽

How can I Access the Outer Scope within Nested Templates in Go?

Accessing Outer Scope within Nested Templates

When working with nested templates in Go, accessing the outer scope from within a "with" or "range" scope can pose a challenge due to the altered scope of the dot (.) variable. To address this, the special variable $ can be employed to access the calling scope.

Consider the following example:

type MyData struct {
  OuterValue string
  InnerValue string
}

func main() {
  data := MyData{OuterValue: "Outer Value", InnerValue: "Inner Value"}
  template.Must(template.New("example").Parse("{{with .Inner}} Outer: {{$.OuterValue}}, Inner: {{.InnerValue}} {{end}}")).Execute(writer, data)
}

In this example, the "with" scope modifies the scope of the dot (.) variable to refer to the "Inner" value of the MyData struct. However, we still need to access the "OuterValue" from within the "with" scope.

To achieve this, we use the $ variable. $ represents the data argument passed to the template during execution, which is identical to the starting value of the dot (.) variable. By using $, we can access the calling scope from within the nested "with" or "range" scope.

The following code demonstrates the usage of $:

$ is documented in the text/template docs:

> When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

以上是如何在 Go 中存取嵌套模板內的外部作用域?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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