Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang template range newline removal

Tags:

templates

go

I'm trying to figure out how I can remove the new lines in my template that are put there by the {{range}} and {{end}}. I get the following output without any of the "-" tags:

type {{makeGoTableName .TableName}} struct {
  {{range $key, $value := .TableData}}
    {{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
  {{end}}
}

Results in:

type Dogs struct {

  ID int64 `db:"id",json:"id"`

  DogNumber int64 `db:"dog_number",json:"dog_number"`

}

If I add the - tags like so, I can get it close to desirable but it breaks the indentation of the final closing brace:

type {{makeGoTableName .TableName}} struct {
  {{range $key, $value := .TableData -}}
    {{makeGoColName $value.ColName}} {{$value.ColType}} `db:"{{makeDBColName $value.ColName}}",json:"{{$value.ColName}}"`
  {{end -}}
}

Results in:

type Dogs struct {
  ID int64 `db:"id",json:"id"`
  DogNumber int64 `db:"dog_number",json:"dog_number"`
  }

Any ideas?

like image 548
b0xxed1n Avatar asked Feb 22 '16 23:02

b0xxed1n


1 Answers

Its mostly on playing with the trailing slash, try

package main

import (
    "os"
    "text/template"
)

type myGreetings struct {
    Greet []string
}

func main() {
    const txt = `
{
        {{- range $index, $word := .Greet}}
  Hello {{$word -}}!!!
        {{- end}}
}
`
    greetText := myGreetings{
        Greet: []string{"World", "Universe", "Gophers"},
    }
    t := template.Must(template.New("Text").Parse(string(txt)))
    t.Execute(os.Stdout, greetText)

}

https://play.golang.org/p/eGm3d3IJPp

Output:

{
  Hello World!!!
  Hello Universe!!!
  Hello Gophers!!!
}
like image 144
David Avatar answered Oct 02 '22 20:10

David