13

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.

tmh
  • 1,385
  • 2
  • 12
  • 18

2 Answers2

20

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.

icza
  • 389,944
  • 63
  • 907
  • 827
  • I'll accept your answer as this is obviously how we expect to solve this since Go 1.6. +1 for also explaining variations. In my case, the problem was an old Go version floating around, which shouldn't normally happen. – tmh Oct 10 '16 at 16:53
1

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

Yandry Pozo
  • 4,851
  • 3
  • 25
  • 27
  • Technically, this solution is correct. However, I'd like to keep the newlines in the template to improve readability. – tmh Oct 10 '16 at 06:08