Home >Backend Development >Golang >How to Print a Period After the Last Array Item in a Go Template?
Detecting the Last Array Item in a Go Template
When iterating over an array in a Go template, a common problem is printing a comma after each element. This can be undesirable when displaying the last element, where a period would be a more suitable ending character.
In the provided code, the template {{range $i, $el := .items}}{{$el}},{{end}} iterates over the items array and prints each element followed by a comma. To print a period after the last element, we need to modify the template.
The solution involves using the if statement to conditionally include the comma. Here's the modified template:
<code class="go">tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."</code>
In this template:
With this template, the program will print the following:
1,4,2.
The last element is correctly ended with a period. This technique of conditionally printing separators is a useful trick for formatting output in Go templates.
The above is the detailed content of How to Print a Period After the Last Array Item in a Go Template?. For more information, please follow other related articles on the PHP Chinese website!