Home >Backend Development >Golang >How to Access the Parent/Global Pipeline in Go Templates' Range Action?

How to Access the Parent/Global Pipeline in Go Templates' Range Action?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 18:34:02247browse

How to Access the Parent/Global Pipeline in Go Templates' Range Action?

Accessing Parent/Global Pipeline in Go Templates' Range Action

In Go's text/template package, the ability to access pipelines prior to a range action or the parent/global pipeline is essential. Consider the following example:

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"}})
}

In this example, accessing .Path won't be possible within the range action because .dot transforms to the current Files element.

Recommended Solution - Using the $ Variable

According to the text/template package documentation, the $ variable holds the data argument passed to Execute, which is the initial value of .dot. Thus, to access the outer scope's Path using $.Path in the range action, use the following variation:

const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`

Alternative Solution - Custom Variable

Prior to the range action, a custom variable can be defined to pass a value into the range scope. For instance:

const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`

The above is the detailed content of How to Access the Parent/Global Pipeline in Go Templates' Range Action?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn