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

前端 未结 2 1869
灰色年华
灰色年华 2020-12-29 01:49

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

相关标签:
2条回答
  • 2020-12-29 02:16

    You can save the calling scope with a variable:

    {{ $save := . }}
    {{ with .Inner }}
      Outer: {{ $save.OuterValue }}
      Inner: {{ .InnerValue }}
    {{ end }}
    
    0 讨论(0)
  • 2020-12-29 02:24
    {{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.

    0 讨论(0)
提交回复
热议问题