Go Templates Whitespace
When writing HTML templates in Go, knowing about the whitespace modifiers is crucial for keeping both the templates and the output HTML looking good.
For example, if you had the following template, with .SomeText
being "foo"
and .Something
being true
:
<a href="/posts">
<span>
{{ if .Something }}
Text
{{ else }}
Image
{{ end }}
</span>
{{ .SomeText }}
</a>
The actual output HTML would look something like:
<a href="/posts"><span> Text </span> foo </a>
Which isn’t what you want, because there’s extra spaces — both around “Text” and around “foo”.
Instead, you could do:
<a href="/posts">
<span>
{{ if .Something }}
{{- Text -}}
{{ else }}
{{- Image -}}
{{ end }}
</span>
{{- .SomeText -}}
</a>
to get
<a href="/posts"><span>Text</span>foo</a>
Which makes both the source code and HTML nice and neat.