Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic in Go templates

I am trying to achieve a very simple thing in a Go template and failing!

The range action allows me to iterate through an array along with its zero-based index, as so:

{{range $index, $element := .Pages}}   Number: {{$index}}, Text: {{element}} {{end}} 

However, I am trying to output indices that start counting from 1. My first attempt failed:

Number: {{$index + 1}} 

This throws an illegal number syntax: "+" error.

I looked into the go-lang official documentation and did not find anything particular regarding the arithmetic operation inside the template.

What am I missing?

like image 450
Ripul Avatar asked Sep 05 '14 15:09

Ripul


1 Answers

You have to write a custom function to do this.

http://play.golang.org/p/WsSakENaC3

package main  import (     "os"     "text/template" )  func main() {     funcMap := template.FuncMap{         // The name "inc" is what the function will be called in the template text.         "inc": func(i int) int {             return i + 1         },     }      var strs []string     strs = append(strs, "test1")     strs = append(strs, "test2")      tmpl, err := template.New("test").Funcs(funcMap).Parse(`{{range $index, $element := .}}   Number: {{inc $index}}, Text:{{$element}} {{end}}`)     if err != nil {         panic(err)     }     err = tmpl.Execute(os.Stdout, strs)     if err != nil {         panic(err)     } } 
like image 169
chendesheng Avatar answered Sep 23 '22 22:09

chendesheng