In Go templates, accessing parent/global pipeline within range

北城余情 提交于 2020-06-08 04:36:53

问题


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


回答1:


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}}`


来源:https://stackoverflow.com/questions/17284222/in-go-templates-accessing-parent-global-pipeline-within-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!