In your first template, you have a newline after the static text "Let's say:"
, and the 2nd line contains only the {{if}}
action, and it also contains a newline, and its body "Hello, StackOverflow!"
starts in the 3rd line. If this is rendered, there will be 2 newlines between the 2 static texts, so you'll see an empty line (as you posted).
You may use {{- if...
to get rid of the first newline, so when rendered, only 1 newline gets to the output, resulting in 2 different lines but no newlines between them:
Let's say:
{{- if eq .Foo "foo" }}
Hello, StackOverflow!
{{- else if eq .Foo "bar" }}
Hello, World!
{{- end }}
Output when Foo
is "foo"
:
Let's say:
Hello, StackOverflow!
Output when Foo
is "bar"
:
Let's say:
Hello, World!
Try it on the Go Playground.
Note that this was added in Go 1.6: Template, and is documented at text/template
: Text and Spaces.
If you use the -
sign at the closing of the actions -}}
, you can even remove all the newlines:
Let's say:
{{- if eq .Foo "foo" -}}
Hello, StackOverflow!
{{- else if eq .Foo "bar" -}}
Hello, World!
{{- end -}}
Output when Foo
is "foo"
and Foo
is "bar"
:
Let's say:Hello, StackOverflow!
Let's say:Hello, World!
Try this one on the Go Playground.
space
between-
andsyntax
. – Transmission