{{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}}{{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.

","image":"http://www.luping.net/uploads/20241110/17312284916730734b51bb5.jpg","datePublished":"2024-11-10T18:28:28+08:00","dateModified":"2024-11-10T18:28:28+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access Parent Pipeline Data within Range in Go Templates?

How to Access Parent Pipeline Data within Range in Go Templates?

Published on 2024-11-10
Browse:564

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}}{{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}}{{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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3