Given this Go text/template code:
Let's say:
{{ if eq .Foo "foo" }}
Hello, StackOverflow!
{{ else if eq .Foo "bar" }}
Hello, World!
{{ end }}
We get the following output in case Foo
equals "foo"
:
Let's say:
Hello, StackOverflow!
(followed by a newline)
Is there a way to get rid of the extra newlines?
I would expect that this can be accomplished using the {{-
and -}}
syntax:
Let's say:
{{- if eq .Foo "foo" }}
Hello, StackOverflow!
{{- else if eq .Foo "bar" }}
Hello, World!
{{- end }}
However, that yields an illegal number syntax: "-"
error.
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.
There is a new line because you're adding a new line after colons (:)
This works https://play.golang.org/p/k4lazGhE-r Note I just start the first if right after the first colons
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With