Home > Article > Backend Development > How Can I Print a Period After the Last Item in a Go Template Range?
Detecting the Last Item in an Array Using Ranges in Go Templates
In Go templates, when iterating over an array using the range directive, it can be difficult to avoid printing a trailing comma after the last item. This can lead to unexpected or incorrect output when rendering data as text.
Problem:
The following Go template outputs commas after each item in an array:
{{range $i, $el := .items}}{{$el}},{{end}}
The desired output, however, is to print a period after the last item:
1,4,2.
Solution:
To print a period after the last item in the array, the template can be modified as follows:
<code class="text">{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}.</code>
The trick here is to use the conditional expression {{if $i}} to emit the comma separator before each item, except for the first one. By adding a period after the closing curly bracket of the range directive, the program ensures that a period is printed after the last item.
This updated template will iterate over the array and print each item with a comma separator, except for the first one. After the last item, a period will be printed instead of a comma.
The above is the detailed content of How Can I Print a Period After the Last Item in a Go Template Range?. For more information, please follow other related articles on the PHP Chinese website!