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.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!