Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 989
Randy Proctor Avatar asked Feb 10 '13 17:02

Randy Proctor


2 Answers

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

like image 95
Testuser Avatar answered Nov 17 '22 10:11

Testuser


You can save the calling scope with a variable:

{{ $save := . }}
{{ with .Inner }}
  Outer: {{ $save.OuterValue }}
  Inner: {{ .InnerValue }}
{{ end }}
like image 30
Randy Proctor Avatar answered Nov 17 '22 12:11

Randy Proctor