How to Start Numbering from 1 in Go Templates?

Barbara Streisand
Release: 2024-11-14 20:01:02
Original
465 people have browsed it

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
}
Copy after login

Register the inc function in a FuncMap. This allows you to use it in the template:

funcMap := template.FuncMap{
    "inc": inc,
}
Copy after login

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}}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template