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
Barbara StreisandOriginal
2024-11-04 09:36:30741browse

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,

However, the desired output is:

1,4,2.

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}}."

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!

Statement:
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