Last Element Treatment in Go's Text Templates
When using Go's text templates to generate a comma-separated list, it becomes necessary to handle the comma placement for the last element differently.
Solution:
The solution involves utilizing a template's ability to assign variables during iteration. By assigning a second variable to the iteration index, we can distinguish the last element from the others. The following template demonstrates this:
{{ $i := . }} ({{ range $i }}{{ . }}, {{if eq $index (len $. - 1)}}{{/* Empty */}}{{else}},{{end}}{{end}})
In this template, we initialize a variable $i to the slice of values passed to the template. Within the range iteration, we assign a second variable $index to the index of each element.
Explanation:
The above is the detailed content of How to Handle the Last Element in Go's Text Template Comma-Separated Lists?. For more information, please follow other related articles on the PHP Chinese website!