How can I avoid unwanted whitespace being added in shortcodes and render hooks?

I have a citation shortcode that (simplified) looks like this:

      {{ with .Params.cite }}cite="{{ . }}"{{ end }}
        {{- with .Params.schemaType -}}
            {{- . -}}
        {{- else -}}
        {{- end -}}"
  <span itemprop="name">{{- .Params.title | safeHTML -}}</span>{{- with 1 -}}{{- end -}}
{{- with .Params.href -}}
{{- end -}}

However, if I don’t include that {{- with 1 -}}{{- end -}} on the fifth-to-last line, the resulting HTML will have a space inserted after the <span> (e.g., <cite ...><span ...>Foo</span> </cite>). There is definitely no errant whitespace character at the end of the line in the shortcode.

I had a similar issue with the render hook for links. The example given in the docs is:

<a href="{{ .Destination | safeURL }}"{{ with .Title }} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank" rel="noopener"{{ end }}>{{ .Text | safeHTML }}</a>

However, unless I add some whitespace removal to the start and end of the template, I ended up with additional spaces being added around every Markdown link. My resulting render hook looks like:

{{- with 1 -}}{{- end -}}<a href="{{ .Destination | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if strings.HasPrefix .Destination "http" }} target="_blank" rel="noreferrer noopener"{{ end }}>{{ .Text | safeHTML }}</a>{{- with 1 -}}{{- end -}}

I’ve also used {{- $foo := 0 -}} before.

Is this an issue to be reported, or expected behaviour? Is there some better way of removing unwanted whitespace (e.g., {{-}}, though that is invalid syntax) than a no-op statement?

Remove leading and trailing whitespace with:

{{- /**/ -}}
1 Like

Could that be made a default by some configuration, at least for html files.
I find it tedious to add - everywhere, and I don’t understand how someone would have a use for seemingly uncontrollable and predictable white-spaces when we can add them manually, and as far as I know they never make sense outside attributes except between <pre> elements or others with a white-space property defined. So it feels like one should annonce white-spaces instead or announcing the need for their removal…
Or maybe I’m projecting my experience.

White space removal is rarely necessary. In production you will minify the HTML.

An example of where white space removal is necessary: shortcodes, partials, or render hooks that return anchor (a) and image (img) elements. These are (by default) inline elements.

If I want to remove white space, I’ll do it myself. I don’t want Hugo doing it for me.


The problem is I caught white-spaces I did not expect. I think with anchor elements, indeed. You are right though :+1:, beside that there’s never been an issue, and it took me an hour to solve, no more.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.