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

2

64

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

Vernalize answered 10/2, 2013 at 17:3 Comment(0)
C
86
{{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.

Constitutional answered 10/2, 2013 at 22:21 Comment(0)
V
30

You can save the calling scope with a variable:

{{ $save := . }}
{{ with .Inner }}
  Outer: {{ $save.OuterValue }}
  Inner: {{ .InnerValue }}
{{ end }}
Vernalize answered 10/2, 2013 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.