是否可以在{{range pipeline}} T1 {{end}}
包中的text/template
操作中访问范围操作之前的管道值,或者将父/全局管道作为参数传递给执行?
显示我尝试做的工作示例:
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"}})
}
答案 0 :(得分:31)
使用$ variable(推荐)
从包text/template文档:
执行开始时,$设置为传递给Execute的数据参数,即dot的起始值。
正如@Sandy指出的那样,因此可以使用$.Path
访问外部作用域中的Path。
const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
使用自定义变量(旧答案)
在发布后几分钟找到一个答案
通过使用变量,可以将值传递到range
范围:
const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`