When I execute template and have multiple for loops I dont get desired behaviour. The template adds a , on last element instead of avoiding it on last element. example code: play.golang.org
Any ideas?
Desired output:
WITH data(name, email, title, sentences) AS (
VALUES
(‘TestName’, ‘test@gmail.com’, ‘Title1’, ARRAY[‘z1 Line 1’, ‘z1 1 Line 2’]),
(‘TestName’, ‘test@gmail.com’, ‘Title1’, ARRAY[‘z2 Line 1’, ‘z2 Line 2’]),
(‘TestName’, ‘test@gmail.com’, ‘Title1’, ARRAY[‘z3 Line 1’, ‘z3 Line 2’])
)
…
package main
import (
"html/template"
"os"
)
func main() {
type Account struct {
Name string
Email string
}
type Sentence struct {
Text string
}
type Object struct {
Sentences []Sentence
}
type List struct {
Account Account
Name string
Objects []Object
}
var list []List
account := Account{Name: "TestName", Email: "test@gmail.com"}
l1 := List{Account: account, Name: "Title1", Objects: []Object{Object{Sentences: []Sentence{Sentence{"z1 Line 1"}, Sentence{"z1 1 Line 2"}}}, Object{Sentences: []Sentence{Sentence{"z2 Line 1"}, Sentence{"z2 Line 2"}}}, Object{Sentences: []Sentence{Sentence{"z3 Line 1"}, Sentence{"z3 Line 2"}}}}}
l2 := List{Account: account, Name: "Title2", Objects: []Object{Object{Sentences: []Sentence{Sentence{"z1 Line 1"}, Sentence{"z1 1 Line 2"}}}, Object{Sentences: []Sentence{Sentence{"z2 Line 1"}, Sentence{"z2 Line 2"}}}}}
l3 := List{Account: account, Name: "Title3", Objects: []Object{Object{Sentences: []Sentence{Sentence{"z1 Line 1"}, Sentence{"z1 1 Line 2"}}}, Object{Sentences: []Sentence{Sentence{"z2 Line 1"}, Sentence{"z2 Line 2"}}}}}
list = append(list, l1, l2, l3)
const insert = `
{{range .}}{{$accName := .Account.Name}}{{$accEmail := .Account.Email}}{{$listTitle := .Name}}
WITH data(name, email, title, sentences) AS (
VALUES {{range $idx, $o := .Objects}}
('{{$accName}}', '{{$accEmail}}', '{{$listTitle}}', ARRAY[{{range $i, $e := $o.Sentences}}{{if $i}}, {{end}}'{{$e.Text}}'{{end}}]){{if $idx}}, {{end}}{{end}}
)
{{end}}
`
t := template.Must(template.New("inserts").Parse(insert))
// Execute the template for each recipient.
err := t.Execute(os.Stdout, list)
if err != nil {
panic(err)
}
}