62

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

Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
Randy Proctor
  • 7,396
  • 3
  • 25
  • 26

2 Answers2

84
{{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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Testuser
  • 1,717
  • 2
  • 16
  • 24
29

You can save the calling scope with a variable:

{{ $save := . }}
{{ with .Inner }}
  Outer: {{ $save.OuterValue }}
  Inner: {{ .InnerValue }}
{{ end }}
Randy Proctor
  • 7,396
  • 3
  • 25
  • 26