Home >Backend Development >Golang >How to Access Parent/Global Pipeline within a Range in Go Templates?
When using a range pipeline ({{range pipeline}} T1 {{end}}) in the text/template package, can the outer pipeline value be accessed prior to the range action or as the parent/global pipeline passed to Execute().
In the following example, we try to access .Path within the range pipeline, but .Path is not available because when the dot is iterating over the Files elements.
package main import ( "os" "text/template" ) // .Path won't be accessible, because dot will be changed to the Files element const page = `{{range .Files}}<script src="{{html .Path}}/js/{{html .}}"></script>{{end}}` type scriptFiles struct { Path string Files []string } func main() { t := template.New("page") t = template.Must(t.Parse(page)) t.Execute(os.Stdout, &scriptFiles{"/var/www", []string{"go.js", "lang.js"}}) }
Using the $ Variable (Recommended)
According to the text/template documentation, at the start of execution, $ is set to the data argument passed to Execute(), which is the starting value of dot. This means that the outer scope's .Path can be accessed using $.Path.
const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
Using a Custom Variable (Legacy Solution)
Another approach is to use a custom variable to pass a value into the range scope, as shown below:
const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`
The above is the detailed content of How to Access Parent/Global Pipeline within a Range in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!