Home > Backend Development > Golang > How to Prevent a Comma After the Last Item in a Go Templates Range?

How to Prevent a Comma After the Last Item in a Go Templates Range?

Barbara Streisand
Release: 2024-11-04 09:36:30
Original
740 people have browsed it

How to Prevent a Comma After the Last Item in a Go Templates Range?

Detecting the Last Item in an Array with Go Templates Range

This program currently prints the following output:

1,4,2,
Copy after login

However, the desired output is:

1,4,2.
Copy after login

Each item in the array is currently being suffixed with a comma. To modify this behavior and ensure that only the last item is suffixed with a period, we can modify the Go template used for iteration:

tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."
Copy after login

The key change is the addition of the {{if $i}},{{end}} statement, which conditionally adds a comma separator.

  • For the first item in the array ($i == 0), the comma is not printed.
  • For subsequent items ($i > 0), the comma is printed.

By placing the comma inside the conditional statement, we ensure that it is only printed for non-first items. The final dot (.), following the end of the range loop, adds the desired period after the last item.

The above is the detailed content of How to Prevent a Comma After the Last Item in a Go Templates Range?. 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