2013-06-24 40 views
12

text/template包中的{{range pipeline}} T1 {{end}}動作中可能訪問範圍操作之前的管道值,還是父/全局管道作爲參數傳遞給Execute?在Go模板中,訪問範圍內的父/全局管道

工作的例子,顯示了我嘗試做:

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

+3

的可能重複[在你如何訪問時的「有」或「範圍」範圍內的外部範圍的模板? ](http://stackoverflow.com/questions/14800204/in-a-template-how-do-you-access-an-outer-scope-while-inside-of-a-with-or-rang) – mcuadros

回答

19

使用變量$(推薦)

從包text/template文檔:

當例如ecution開始,$被設置爲傳遞給Execute的數據參數,也就是點的起始值。

作爲@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}}` 
+13

你可以使用$ .Path訪問外部作用域(請參閱http://stackoverflow.com/questions/14800204/in-a-template-how-do-you-access-an-outer-scope-while-inside-of-a -with-or-rang?rq = 1) – Sandy