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

Patricia Arquette
Release: 2024-11-01 07:17:30
Original
289 people have browsed it

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>
Copy after login

This program outputs the following:

1,4,2,
Copy after login

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

1,4,2.
Copy after login
Copy after login

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

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

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.
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template