Arithmetic in Go templates

Ripul picture Ripul · Sep 5, 2014 · Viewed 25k times · Source

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?

Answer

chendesheng picture chendesheng · Sep 5, 2014

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)
    }
}