Home >Backend Development >Golang >How to Prevent a Trailing Comma in Go Template Array Output?
In a Go template, you might encounter a situation where you need to print an array without a trailing comma after the last item.
Consider the following code:
<code class="go">package main import "os" import "text/template" func main() { params := map[string]interface{}{ "items": [3]int{1, 4, 2}, } tpl := "{{range $i, $el := .items}}{{$el}},{{end}}" lister, _ := template.New("foo").Parse(tpl) lister.Execute(os.Stdout, params) }</code>
This code outputs:
1,4,2,
To remove the trailing comma, you can modify the template to:
<code class="go">tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."</code>
The critical change here is the introduction of the conditional statement {{if $i}},{{end}} inside the range loop. Let's break down what this does:
The above is the detailed content of How to Prevent a Trailing Comma in Go Template Array Output?. For more information, please follow other related articles on the PHP Chinese website!