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

感情迁移 提交于 2019-11-29 10:37:45

问题


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


回答1:


{{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:


You can save the calling scope with a variable:

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


来源:https://stackoverflow.com/questions/14800204/in-a-template-how-do-you-access-an-outer-scope-while-inside-of-a-with-or-rang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!