在模板中,当处于“with”或“range”作用域内时,如何访问外部作用域?

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

In a template how do you access an outer scope while inside of a "with" or "range" scope?

问题

当在withrange中时,.的作用域会发生变化。如何访问调用的作用域?

英文:

When inside a with or range, the scope of . is changed. How do you access the calling scope?

答案1

得分: 84

{{with .Inner}}
外部: {{$.OuterValue}}
内部: {{.InnerValue}}
{{end}}

$text/template 文档中有详细说明:

> 当执行开始时,$ 被设置为传递给 Execute 的数据参数,也就是 dot 的初始值。

英文:
{{with .Inner}}
  Outer: {{$.OuterValue}}
  Inner: {{.InnerValue}}
{{end}}

$ is documented in the text/template docs:

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

答案2

得分: 29

你可以使用一个变量保存调用范围:

{{ $save := . }}
{{ with .Inner }}
  外部值:{{ $save.OuterValue }}
  内部值:{{ .InnerValue }}
{{ end }}
英文:

You can save the calling scope with a variable:

{{ $save := . }}
{{ with .Inner }}
  Outer: {{ $save.OuterValue }}
  Inner: {{ .InnerValue }}
{{ end }}

huangapple
  • 本文由 发表于 2013年2月11日 01:03:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/14800204.html
匿名

发表评论

匿名网友

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

确定