Home >Backend Development >Golang >How to Remove Trailing Commas in Go Template Range Loops Without Custom Functions?

How to Remove Trailing Commas in Go Template Range Loops Without Custom Functions?

DDD
DDDOriginal
2024-12-07 18:26:13767browse

How to Remove Trailing Commas in Go Template Range Loops Without Custom Functions?

Removing Commas in Range Loop Templates with Go

In Go template loops, a comma often appears after each iteration, separating the output. For instance:

key:a value:b, key:c value:d,

To eliminate this comma, a solution is sought that doesn't use custom functions.

Answer:

As of Go 1.11, it's possible to directly modify template variables. This enables comma removal through the following template:

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

Within this template, a variable $first is initialized to true. During the loop, it checks if this is the first iteration, and if so, sets $first to false to prevent commas on subsequent iterations.

Example:

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)

Output:

key:a value:b, key:c value:d, key:e value:f

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