Home > Mobile >  Avoid `{{- ... }}` Trim Extra Leading Whitespace in text/template of Golang?
Avoid `{{- ... }}` Trim Extra Leading Whitespace in text/template of Golang?

Time:10-01

I attempt to render markdown list with text/template package of Go, and need to omit list items if the value is empty.

For example:

Full list rendering result:

# Debug Template 1

- Item A: Apple
- Item B: Bosch
- Item C: Cocola
- Item D: Delta
- Item E: Ellie

Expected result when B and D is empty:

# Debug Template 1

- Item A: Apple
- Item C: Cocola
- Item E: Ellie

So based on my full template:

# Debug Template 1

- Item A: {{ .ItemA }}
- Item B: {{ .ItemB }}
- Item C: {{ .ItemC }}
- Item D: {{ .ItemD }}
- Item E: {{ .ItemE }}

I tried to use {{- ...}} syntax to avoid newline, but it trimmed too much, and the newlines before the {{- if ...}} is also trimmed.

i.e. for the template (intentionally two newlines to demo this):

# Debug Template 2


{{- if .ItemA }}- Item A: {{ .ItemA }}
{{ end }}
{{- if .ItemB }}- Item B: {{ .ItemB }}
{{ end }}
{{- if .ItemC }}- Item C: {{ .ItemC }}
{{ end }}
{{- if .ItemD }}- Item D: {{ .ItemD }}
{{ end }}
{{- if .ItemE }}- Item E: {{ .ItemE }}
{{ end }}

Result:

# Debug Template 2- Item A: Apple
- Item B: Bosch
- Item C: Cocola
- Item D: Delta
- Item E: Ellie

Here's the code snippet:

package main

import (
    "os"
    "text/template"
)

func DemoRenderIssue() error {
    data := struct {
        ItemA string
        ItemB string
        ItemC string
        ItemD string
        ItemE string
    }{
        ItemA: "Apple",
        // ItemB: "Bosch",
        ItemC: "Cocola",
        // ItemD: "Delta",
        ItemE: "Ellie",
    }
    tmplStr := `
# Debug Template 1

- Item A: {{ .ItemA }}
- Item B: {{ .ItemB }}
- Item C: {{ .ItemC }}
- Item D: {{ .ItemD }}
- Item E: {{ .ItemE }}

# Debug Template 2


{{- if .ItemA }}- Item A: {{ .ItemA }}
{{ end }}
{{- if .ItemB }}- Item B: {{ .ItemB }}
{{ end }}
{{- if .ItemC }}- Item C: {{ .ItemC }}
{{ end }}
{{- if .ItemD }}- Item D: {{ .ItemD }}
{{ end }}
{{- if .ItemE }}- Item E: {{ .ItemE }}
{{ end }}
`
    tmpl, err := template.New("demo").Parse(tmplStr)
    if err != nil {
        return err
    }
    return tmpl.Execute(os.Stdout, &data)
}

Can you please tell me how to fix the template or other skills to get the expected result?

CodePudding user response:

Just make sure to keep the first newline:

# Debug Template 2

{{ if .ItemA }}- Item A: {{ .ItemA }}
{{ end }}
...

As the documentation states, {{- will clear all preceding whitespaces. In your case, using {{- if .ItemA... will clear all whitespaces up to the end of the string Template 2 (newline is a whitespace). Simply keeping the first item in the list as {{if .ItemA}} preserves all whitespaces up to that point.

  • Related