Home >Backend Development >Golang >How to Prevent a Trailing Comma in Go Template Array Output?

How to Prevent a Trailing Comma in Go Template Array Output?

DDD
DDDOriginal
2024-11-02 11:58:02914browse

How to Prevent a Trailing Comma in Go Template Array Output?

Detect Last Item in an Array Using Range in Go Templates

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:

  • {{range $i, $el := .items}}: This line initiates a loop over the items array, where $i represents the index and $el represents the current item.
  • {{if $i}},{{end}}: Inside the loop, this conditional checks whether it's not the first item in the array. If it's not the first item ($i is not 0), it prints a comma.
  • {{.el}}: This part prints the current item in the array.
  • {{end}}: This line ends the loop.
  • . at the end of the template: Finally, we add a period (".") to the end of the template to terminate the output.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn