Access out of loop value inside golang template's loop

TemplatesGo

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

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
QuestionDenys S&#233;guretView Question on Stackoverflow
Solution 1 - TemplateschoweyView Answer on Stackoverflow
Solution 2 - TemplatescreackView Answer on Stackoverflow
Solution 3 - TemplatesDenys SéguretView Answer on Stackoverflow