Home > Article > Backend Development > How to Start Numbering from 1 in Go Templates?
Numbering with Go Templates
In Go templates, the range action facilitates iteration over arrays, providing access to the index and element for each item. However, by default, indices start from 0. This article will guide you through creating a custom function to generate indices starting from 1.
The allowed syntax for arithmetic operations within templates is limited. To overcome this, you can create a custom function called inc to increment the index by 1.
Here's how to implement the solution:
func inc(i int) int { return i + 1 }
Register the inc function in a FuncMap. This allows you to use it in the template:
funcMap := template.FuncMap{ "inc": inc, }
To use the custom function, edit your template to utilize the inc function within the range loop:
{{range $index, $element := .}} Number: {{inc $index}}, Text:{{$element}} {{end}}
This will output indices that increment from 1.
For a more detailed example, check out the provided code snippet at http://play.golang.org/p/WsSakENaC3.
The above is the detailed content of How to Start Numbering from 1 in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!