Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access out of loop value inside golang template's loop

Tags:

templates

go

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.

like image 648
Denys Séguret Avatar asked May 24 '13 12:05

Denys Séguret


2 Answers

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".)

like image 100
chowey Avatar answered Sep 22 '22 03:09

chowey


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}} 
like image 30
creack Avatar answered Sep 22 '22 03:09

creack