Display counter on html template in Go

Using html / templates in Go, you can do the following:

<table class="table table-striped table-hover" id="todolist"> {{$i:=1}} {{range .}} <tr> <td><a href="id/{{.Id}}">{{$i}}</a></td> <td>{{.Title}}</td> <td>{{.Description}}</td> </tr> {{$i++}} {{end}} </table> 

every time I add the variable $ i, the application shuts down.

+7
source share
2 answers

In my html template :

 <table class="table table-striped table-hover" id="todolist"> {{range $index, $results := .}} <tr> <td>{{add $index 1}}</td> <td>{{.Title}}</td> <td>{{.Description}}</td> </tr> {{end}} </table> 

In the go code, I wrote a function that I passed to FuncMap:

 func add(x, y int) int { return x + y } 

In my handler:

 type ToDo struct { Id int Title string Description string } func IndexHandler(writer http.ResponseWriter, request *http.Request) { results := []ToDo{ToDo{5323, "foo", "bar"}, ToDo{632, "foo", "bar"}} funcs := template.FuncMap{"add": add} temp := template.Must(template.New("index.html").Funcs(funcs).ParseFiles(templateDir + "/index.html")) temp.Execute(writer, results) } 
+12
source

Check out Variables section text/template

http://golang.org/pkg/text/template/

 range $index, $element := pipeline 
+9
source

All Articles