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