在Go模板中,访问范围内的父/全局管道 [英] In Go templates, accessing parent/global pipeline within range
问题描述
在text/template
包中的{{range pipeline}} T1 {{end}}
动作中,是否可以在range动作之前访问管道值,还是可以将父/全局管道作为参数传递给Execute?
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"}})
}
推荐答案
使用$变量(推荐)
从软件包文本/模板文档中:
执行开始时,将$设置为传递给Execute的data参数,即dot的起始值.
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
正如@Sandy所指出的,因此可以使用$.Path
访问外部作用域中的Path.
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}}`
使用自定义变量(旧答案)
发布后几分钟就找到了一个答案.
通过使用变量,可以将值传递到range
范围:
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}}`
这篇关于在Go模板中,访问范围内的父/全局管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!