How to avoid new lines caused by conditional expressions?

Given this Go text / template code:

Let say:
{{ if eq .Foo "foo" }}
Hello, StackOverflow!
{{ else if eq .Foo "bar" }}
Hello, World!
{{ end }}

We get the following result if Fooequal to "foo":

Let say:

Hello, StackOverflow!

(followed by a new line)

Is there a way to get rid of extra lines of a new line?

I would expect this to be possible with the syntax {{-and -}}:

Let say:
{{- if eq .Foo "foo" }}
Hello, StackOverflow!
{{- else if eq .Foo "bar" }}
Hello, World!
{{- end }}

However, this leads to an error illegal number syntax: "-".

+3
source share
2 answers

"Let say:", {{if}}, , "Hello, StackOverflow!" , , , ( ).

{{- if..., , 1 , , :

Let say:
{{- if eq .Foo "foo" }}
Hello, StackOverflow!
{{- else if eq .Foo "bar" }}
Hello, World!
{{- end }}

, Foo "foo":

Let say:
Hello, StackOverflow!

, Foo "bar":

Let say:
Hello, World!

Go Playground.

, 1.6: text/template: .

- -}}, :

Let say:
{{- if eq .Foo "foo" -}}
Hello, StackOverflow!
{{- else if eq .Foo "bar" -}}
Hello, World!
{{- end -}}

, Foo "foo", Foo - "bar":

Let say:Hello, StackOverflow!
Let say:Hello, World!

.

+1
0

Source: https://habr.com/ru/post/1657226/


All Articles