43

Is it possible, within a {{range pipeline}} T1 {{end}} action in the text/template package to access the pipelines value prior to the range action, or the parent/global pipeline passed as an argument to Execute?

Working example that shows what I try to do:

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

play.golang.org

ANisus
  • 74,460
  • 29
  • 162
  • 158
  • 4
    possible duplicate of [In a template how do you access an outer scope while inside of a "with" or "range" scope?](http://stackoverflow.com/questions/14800204/in-a-template-how-do-you-access-an-outer-scope-while-inside-of-a-with-or-rang) – mcuadros May 01 '15 at 20:44

1 Answers1

68

Using the $ variable (recommended)

From the package text/template documentation:

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

As @Sandy points out, it is therefore possible to access the Path in the outer scope using $.Path.

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

Using a custom variable (old answer)

Found one answer just minutes after posting.
By using a variable, a value can be passed into the range scope:

const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`
ANisus
  • 74,460
  • 29
  • 162
  • 158
  • 17
    You can access the outer scope with $.Path (see http://stackoverflow.com/questions/14800204/in-a-template-how-do-you-access-an-outer-scope-while-inside-of-a-with-or-rang?rq=1 ) – Sandy Sep 29 '13 at 16:25
  • 1
    Thanks for keeping the old answer, it's still useful when we need to access a parent of parent. – Slava Semushin Aug 13 '19 at 10:00