Within the text/template package, developers may encounter the need to access pipeline values before a range action or to utilize the parent/global pipeline passed to Execute. This article delves into this requirement, providing solutions and examining potential approaches.
Using the $ Variable (Recommended)
According to the text/template documentation, "$" initially refers to the data argument provided to Execute, the starting dot value. Consequently, accessing the outer scope is possible using $.Path, as suggested by @Sandy.
const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
Custom Variable Approach (Legacy Answer)
Alternatively, a variable can be introduced to pass values into the range scope, as specified below:
const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`
This approach allows for greater flexibility in variable naming and scope management. However, using "$" is highly recommended for its simplicity and elegance.
The above is the detailed content of How to Access Parent/Global Pipeline Within Range in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!