Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In a Go template, how to add a line with a string value only if that value is non-empty?

I’d like to render a template with a struct containing a certain string field, say a Restaurant with a Name, such that if the Name is non-empty, it is printed on a line, but if it is empty, that line is absent. So far, I’ve tried

package main

import (
    "os"
    "text/template"
)

type Restaurant struct {
    Name string
}

func main() {
    tmpl, err := template.New("test").Parse(`The restaurant is:
{{if .Name }}{{.Name}}{{ end }}
The end.
`)
    if err != nil {
        panic(err)
    }

    if err := tmpl.Execute(os.Stdout, Restaurant{Name: ""}); err != nil {
        panic(err)
    }
}

This prints

The restaurant is:

The end.

However, I want the blank line in the middle to be omitted in that case:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The restaurant is:
The end.

When the name is non-empty, however, I want the line to be present: if I used Restaurant{Name: "Itria"} in the tmpl.Execute argument, the output should be

The restaurant is:
Itria
The end.

I’ve read https://pkg.go.dev/text/template#hdr-Text_and_spaces but it is unclear to me how to use the minus sign before and after action delimiters to achieve this.

>Solution :

You want the newline rendered conditionally, if .Name is not empty. So move a newline inside the {{if}} block, and do not render (leave) a newline after the {{if}} block (try it on the Go Playground):

    tmpl, err := template.New("test").Parse(`The restaurant is:
{{if .Name }}{{.Name}}
{{end}}The end.
`)

Or another solution (try this one on the Go Playground):

    tmpl, err := template.New("test").Parse(`The restaurant is:
{{if .Name }}{{.Name}}
{{ end -}}
The end.
`)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading