How to Start Go Template Indexes from 1?

Susan Sarandon
Release: 2024-11-12 03:06:02
Original
268 people have browsed it

How to Start Go Template Indexes from 1?

Custom Arithmetic Functions in Go Templates

In Go templates, the range action provides a convenient way to iterate through collections and access both the index and the element. However, the default index starts from 0. To achieve a more human-friendly numbering system starting from 1, a custom function can be defined.

Implementing the Custom Function

The key is to extend the template's built-in function map with a new function. In the example provided, the function is named "inc" and takes an integer as an argument. Within the function, a simple increment operation is performed.

func inc(i int) int {
    return i + 1
}
Copy after login

Applying the Function in the Template

Once the custom function is defined, it can be invoked within the template using the following syntax:

{{inc $index}}, Text: {{element}}
Copy after login

This line calculates the incremented index and displays it as "Number:" before the actual element.

Example Usage

Consider an array of strings:

var strs []string
strs = append(strs, "test1")
strs = append(strs, "test2")
Copy after login

When the template is executed with this array, the output would look like:

Number: 1, Text: test1
Number: 2, Text: test2
Copy after login

Demonstrating the successful modification of the index values to start from 1 instead of 0.

The above is the detailed content of How to Start Go Template Indexes from 1?. 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