在Go模板中,在range循环中访问父级/全局管道。

huangapple go评论81阅读模式
英文:

In Go templates, accessing parent/global pipeline within range

问题

text/template包中的{{range pipeline}} T1 {{end}}操作中,是否可以访问range操作之前的pipeline的值,或者作为参数传递给Execute的父/全局pipeline?

展示了我尝试做的工作示例:

package main

import (
    "os"
    "text/template"
)

// .Path将无法访问,因为点将被更改为Files元素
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

英文:

Is it possible, within a {{range pipeline}} T1 {{end}} action in the text/template package to access the pipelines value prior to the range action, or the parent/global pipeline passed as an argument to Execute?

Working example that shows what I try to do:

package main

import (
	&quot;os&quot;
	&quot;text/template&quot;
)

// .Path won&#39;t be accessible, because dot will be changed to the Files element
const page = `{{range .Files}}&lt;script src=&quot;{{html .Path}}/js/{{html .}}&quot;&gt;&lt;/script&gt;{{end}}`

type scriptFiles struct {
	Path string
	Files []string
}

func main() {
	t := template.New(&quot;page&quot;)
	t = template.Must(t.Parse(page))
	
	t.Execute(os.Stdout, &amp;scriptFiles{&quot;/var/www&quot;, []string{&quot;go.js&quot;, &quot;lang.js&quot;}})
}

play.golang.org

答案1

得分: 68

使用$变量(推荐)

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}}`
英文:

Using the $ variable (recommended)

From the package text/template documentation:

>When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

As @Sandy points out, it is therefore possible to access the Path in the outer scope using $.Path.

const page = `{{range .Files}}&lt;script src=&quot;{{html $.Path}}/js/{{html .}}&quot;&gt;&lt;/script&gt;{{end}}`

Using a custom variable (old answer)

Found one answer just minutes after posting.
By using a variable, a value can be passed into the range scope:

const page = `{{$p := .Path}}{{range .Files}}&lt;script src=&quot;{{html $p}}/js/{{html .}}&quot;&gt;&lt;/script&gt;{{end}}`

huangapple
  • 本文由 发表于 2013年6月25日 04:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/17284222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定