Home > Backend Development > Golang > How can I Access the Outer Scope within Nested Templates in Go?

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

Mary-Kate Olsen
Release: 2024-11-15 11:38:02
Original
773 people have browsed it

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)
}
Copy after login

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.
Copy after login

The above is the detailed content of How can I Access the Outer Scope within Nested Templates in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template