是否有可能{{range pipeline}} T1 {{end}}在text/template包中的操作中訪問范圍操作之前的管道值,或者作為參數傳遞給 Execute 的父/全局管道?顯示我嘗試做的工作的示例:package mainimport ( "os" "text/template")// .Path won't be accessible, because dot will be changed to the Files elementconst 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"}})}https://play.golang.org/p/gO6w0o3FeP
1 回答

慕村225694
TA貢獻1880條經驗 獲得超4個贊
使用 $ 變量(推薦)
從包文本/模板文檔:
執行開始時,$ 設置為傳遞給 Execute 的數據參數,即 dot 的起始值。
正如@Sandy 指出的那樣,因此可以使用$.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}}`
- 1 回答
- 0 關注
- 204 瀏覽
添加回答
舉報
0/150
提交
取消