Home >Backend Development >Golang >How to Access Parent Pipeline Data within Range in Go Templates?
Accessing Parent Pipeline within Range in Template Actions
In Go templates, it's common to use range pipelines to iterate through slices or maps. However, a frequent problem arises when trying to access data outside the immediate scope of the pipeline. This article explores how to achieve this.
Using the $ Variable (Recommended)
The text/template documentation specifies that when execution begins, the $ variable references the data argument passed to Execute. This means we can access the outer scope data by using $.variable.
For example, consider this template:
const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
Here, .Files refers to a slice of files, but we want to access the Path of the enclosing scriptFiles struct. Using $.Path allows us to do that.
Using a Custom Variable (Legacy Method)
An alternative method involves creating a custom variable to pass into the range scope, as demonstrated in this template:
const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`
By setting $p to .Path before the range pipeline, we can access the path within the pipeline.
Note: The $ variable method is recommended as it's the more concise and idiomatic approach in current Go versions.
The above is the detailed content of How to Access Parent Pipeline Data within Range in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!