Home >Backend Development >Golang >How to Avoid Trailing Commas in Go Text Template String Concatenation?

How to Avoid Trailing Commas in Go Text Template String Concatenation?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 15:08:13303browse

How to Avoid Trailing Commas in Go Text Template String Concatenation?

Special Case Handling for Last Element in Go Text Templates

In Go's text templating system, creating strings such as "(p1, p2, p3)" from an array can be challenging, especially when placing commas correctly for the last element.

Non-Working Attempt

One attempt that fails to remove the trailing comma is:

import (
    "text/template"
    "os"
)

func main() {
    ip := []string{"p1", "p2", "p3"}
    temp := template.New("myTemplate")
    _, _ = temp.Parse(paramList)
    temp.Execute(os.Stdout, ip)
}

const paramList = "{{ $i := . }}({{ range $i }}{{ . }}, {{end}})"

Solution

This puzzle can be solved by leveraging the special syntax of template if statements. Unlike Go if statements, template ifs can test for zero values. This allows for the following trick:

import (
    "text/template"
    "os"
)

func main() {
    ip := []string{"p1", "p2", "p3"}
    temp := template.New("myTemplate")
    _, _ = temp.Parse(paramList)
    temp.Execute(os.Stdout, ip)
}

const paramList = "{{ $i := . }}({{ range $i }}{{ if $index }},{{end}}{{ . }}{{end}})"

The magic lies in the line:

{{ if $index }},{{end}}

The $index variable is automatically assigned during the range iteration and is used to test for the last element. If the index is non-zero (meaning not the last element), a comma is inserted. This ensures that the last element does not have a trailing comma.

The above is the detailed content of How to Avoid Trailing Commas in Go Text Template String Concatenation?. 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