Home > Backend Development > Golang > How to Remove the Trailing Comma in Go Template Range Loops?

How to Remove the Trailing Comma in Go Template Range Loops?

Barbara Streisand
Release: 2024-12-09 17:19:09
Original
392 people have browsed it

How to Remove the Trailing Comma in Go Template Range Loops?

Go Template: Removing the Last Comma in a Range Loop

In Go templates, when iterating over a range of elements, a comma is automatically appended after each element. This can be undesirable in certain scenarios, such as when generating a list of values without the final trailing comma.

One way to remove the last comma is by accessing the index of the element during the range loop. However, this approach is not applicable to maps because they do not provide an index for their elements.

Solution Using Go 1.11

Since Go 1.11, it is possible to modify the values of template variables within the template itself. This allows for removing the last comma with the following template:

{{$first := true}}
{{range $key, $value := $}}
    {{if $first}}
        {{$first = false}}
    {{else}}
        ,
    {{end}}
    key:{{$key}} value:{{$value}}
{{end}}
Copy after login

The template defines a variable $first that is set to true initially. During the range loop, if $first is true, it is set to false and no comma is added. For all subsequent iterations, a comma is added before the element.

Modified Example

Here's an updated version of the example from the question that removes the final comma using the above technique:

type Map map[string]string
m := Map{
    "a": "b",
    "c": "d",
    "e": "f",
}
const temp = `{{$first := true}}{{range $key, $value := $}}{{if $first}}{{$first = false}}{{else}}, {{end}}key:{{$key}} value:{{$value}}{{end}}`
t := template.Must(template.New("example").Parse(temp))
t.Execute(os.Stdout, m)
Copy after login

This template will output the following:

key:a value:b, key:c value:d, key:e value:f
Copy after login

The above is the detailed content of How to Remove the Trailing Comma in Go Template Range Loops?. 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