Home > Backend Development > Golang > How to Access Parent/Global Pipeline within a Range in Go Templates?

How to Access Parent/Global Pipeline within a Range in Go Templates?

Susan Sarandon
Release: 2024-11-12 08:18:02
Original
705 people have browsed it

How to Access Parent/Global Pipeline within a Range in Go Templates?

Accessing Parent/Global Pipeline within Range in Go Templates

Problem

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().

Working Example

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"}})
}
Copy after login

Solutions

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}}`
Copy after login

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}}`
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template