template package conditional comma

4,663 views
Skip to first unread message

Greg Worley

unread,
Oct 28, 2011, 2:18:52 PM10/28/11
to golan...@googlegroups.com
I'm wondering how to write a template that will add a comma at the end of each line unless it's the last line.

for example:

line 1,
line 2,
line 3


Message has been deleted

Greg Worley

unread,
Oct 28, 2011, 4:18:15 PM10/28/11
to golan...@googlegroups.com
hmm, and :

package main

import (
"template"
"os"
"fmt"
)

const templStr = `{{range $i, $e := $}}{{if $i}},{{end}}{{$e}}{{end}}`

func main() {
fmt.Println("start")
 t := template.Must(template.New("example").Parse(templStr))
 t.Execute(os.Stdout, []string{"line 1", "line 2", "line 3"})
  }

outputs:

start
line 1,line 2,line 3

Message has been deleted

gregworley

unread,
Oct 28, 2011, 10:54:02 PM10/28/11
to golang-nuts
thanks!

On Oct 28, 7:36 pm, D Smithson <d_smith...@rocketmail.com> wrote:
> Here's the template that produces the output specified in the original mail
> (one string per line with comma at end of each line except last)
>
> var templStr = `{{range $i, $e := $}}{{if $i}},
> {{end}}{{$e}}{{end}}
> `
Reply all
Reply to author
Forward
0 new messages