why dash is used in condition Go templates
Asked Answered
C

1

37

I've seen many examples of dash being use for if statements ("{{- if.."), e.g:

{{- if hasKey .Values.mymap "mykey" }}
    # do something conditional here...
{{- end }}

what is the purpose of the dash in that statement?

Cannon answered 6/1, 2020 at 6:29 Comment(0)
G
47

Dash removes the spaces from the output on the side it appears in the template:

https://golang.org/pkg/text/template/#hdr-Text_and_spaces

{{- if ...}}

The above will remove all spaces that appear before the if statement, so if the result of if prints something, it'll be right after the last piece of text without any spaces.

Gaffrigged answered 6/1, 2020 at 6:34 Comment(8)
in that case, what is the point behind the dash in {{- end }}?Cannon
Removes all spaces after the output of the if body, so the output after {{-end}} now immediately follows the last printed non-space character in the if-body.Gaffrigged
what if move - before the closing bracket? does it make any difference?Eal
@LeiYang, That will remove all spaces after the closing bracket.Gaffrigged
then what's the difference between right dash in first line, and left dash in second line?Eal
@LeiYang I don't understand the question, but if you look at the link in the answer, it should make things clear.Gaffrigged
i cannot open that link(in china). i mean, {{ end -}} \n {{ end }} vs {{ end }} \n {{- end }} is there any difference, and which is preferable?Eal
Newline is a space character so both will yield the same result. If it was a different character, the first one will remove the spaces before that character, the second one will remove spaces after.Gaffrigged

© 2022 - 2024 — McMap. All rights reserved.