Arithmetic in Go templates

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

Leave a Comment

tech