To access the parent or global pipeline value within a range action in the text/template package, there are two main methods:
Using the $ Variable (Recommended)
According to the text/template documentation, when execution begins, the $ variable is set to the data argument passed to Execute, effectively representing the starting value of the dot. This allows access to the outer scope variables, including the parent/global pipeline. For instance, to access the Path in the outer scope, use $.Path.
const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
Using a Custom Variable (Legacy Approach)
Alternatively, a custom variable can be created to pass values into the range scope:
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 Values within Range in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!