2013-06-24 106 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