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:
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.
`)