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!