Access out of loop value inside golang template's loop
TemplatesGoTemplates Problem Overview
I have this struct :
type Site struct {
Name string
Pages []int
}
I pass an instance of Site
to a template.
If I want to write a list of all pages, I do
{{range .Pages}}
<li><a href="{{.}}">{{.}}</a></li>
{{end}}
Now, what's the simplest way to use the Name
field inside the loop (for example to change the href
to Name/page
) ?
Note that a solution based on the fact that the external object is the global one that was passed to the template would be OK.
Templates Solutions
Solution 1 - Templates
You should know that the variable passed in to the template is available as $
.
{{range .Pages}}
<li><a href="{{$.Name}}/{{.}}">{{.}}</a></li>
{{end}}
(See the text/template documentation under "Variables".)
Solution 2 - Templates
What about:
{{$name := .Name}}
{{range $page := .Pages}}
<li><a href="{{$name}}/{{$page}}">{{$page}}</a></li>
{{end}}
Or simply make Pages
a map with Name as value?
type Site struct {
Pages map[string]string
}
{{range $page, $name := .Pages}}
<li><a href="{{$name}}/{{$page}}">{{$page}}</a></li>
{{end}}
Solution 3 - Templates
It looks like there's no simpler solution than to explicitly declare a variable for the outer object (or its properties) :
{{$out := .}}
{{range .Pages}}
<li><a href="{{$out.Name}}/{{.}}">{{.}}</a></li>
{{end}}
EDIT : this answer isn't the right one any more, look at chowey's one instead.