Access out of loop value inside golang template's loop
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.
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".)
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}}