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.
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!