Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid newlines caused by conditionals?

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.

like image 613
tmh Avatar asked Oct 09 '16 20:10

tmh


2 Answers

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.

like image 151
icza Avatar answered Nov 18 '22 22:11

icza


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

like image 25
Yandry Pozo Avatar answered Nov 18 '22 22:11

Yandry Pozo