Hugo range function adds extra whitespace between spans

{{range (slice 1 2) }}
  <span>foo</span>
  <span>bar</span>
{{end}}

Results in

<span>foo</span>
[whitespace]
<span>bar</span>
[whitespace]
<span>foo</span>
[whitespace]
<span>bar</span>

Is this intentional? Is there a way to not generate the whitespace node?

The following link from the documentation describes how to remove the unwanted whitespace:

I’m not talking about whitespaces as in multiple space characters to be trimmed using {{- -}}, what I get is displayed in Firefox Developer Tools as a whitespace node, which is, unfortunately, not removable with the dash sign mentioned above.

Does writing it this way make a difference?

{{range (slice 1 2) }}<span>foo</span><span>bar</span>{{end}}

This is weird, I’m suddenly not getting them in the example above anymore.
Now I get those whitespace nodes if I wrap the provided example in a div or an ul or something.

Now back to your reply, yes writing them on the same line removes the whitespace node.
That works for this short example, but my real use case is a bit more complex, with both spans coming from different partials. Writing everything on the same line would be quite a messy format.

EDIT:
Actually, while the said solution does fix this simple example, it does not fix my real use case, even when I changed all related partials to be one-liners.

Does the rendered HTML in the browser look as expected?

Trying to nail down if you only see this “whitespace node” in devtools.

The rendered HTML has that whitespace, which was the reason I looked at the devtools.

Okay after few tests, I can confirm that this issue is with newline characters around span tag. It has nothing to do with range function, or hugo itself at all. This is a HTML thing. I get the whitespace in HTML with the minimum code below

<html>
<body><div>
    <span>foo</span>
    <span>bar</span>
</div></body></html>

So any newline character between two spans will create a whitespace node, and by removing the newline between the two spans will remove the whitespace node.

The workaround is mentioned in html - how to remove the white space between two span tags? - Stack Overflow.

I guess the Hugo way is to use a placeholder function, such as {{- .Scratch -}} or {{- if false -}}{{- end -}}, I don’t know which is less costly on performance.

A related article:
When does white space matter in HTML? | by Patrick Brosset | Medium

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