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

GoGo Templates

Go Problem Overview


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

Go Solutions


Solution 1 - Go

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

Solution 2 - Go

You can save the calling scope with a variable:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRandy ProctorView Question on Stackoverflow
Solution 1 - GoTestuserView Answer on Stackoverflow
Solution 2 - GoRandy ProctorView Answer on Stackoverflow