Home  >  Article  >  Backend Development  >  How to Avoid a Comma After the Last Element in a Go Template Range?

How to Avoid a Comma After the Last Element in a Go Template Range?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 07:17:30198browse

How to Avoid a Comma After the Last Element 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 keyword, a comma separator is automatically inserted between each element. While this behavior is useful in most cases, it can become a problem when the desired output requires a period rather than a comma after the last element.

Consider the following program:

<code class="go">package main

import (
    "os"
    "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 program outputs the following:

1,4,2,

Note that there is a comma after the last element (2). However, we would prefer the output to be:

1,4,2.

To achieve this, we can modify the template as follows:

<code class="go">tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."</code>

The key difference here is the introduction of the {{if $i}},{{end}} construct. This conditional statement checks if the current loop iteration is not the first one, and if it is, it emits a comma. This ensures that a comma is only inserted between elements in the array, and not after the last element.

By incorporating this change, the program will now output:

1,4,2.

The above is the detailed content of How to Avoid a Comma After the Last Element in a Go Template Range?. 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