HUGO

Remove all elements from slice

I apologize if this is widely known or trivial. But since it took me several days to figure out… To remove all elements from a slice, you can use

$mySlice = first 0 $mySlice

Assigning to it like this

$mySlice = slice

does not work, although $mySlice := slice creates an empty slice. If there’s another obvious way to achieve this, I’d be glad to hear about it.

Background: I needed slices to collect information about subgroups in a taxonomy term and output at the end of the subgroup’s listings. After each subgroup, the slices had to be cleared for the next one.

Unless I’m missing something, that works just fine.

{{ $s := slice }}
$s has {{ $s | len }} elements <br>
{{ $s = $s | append "foo" }}
$s has {{ $s | len }} elements <br>
{{ $s = $s | append "bar" }}
$s has {{ $s | len }} elements <br>
{{ $s = slice }}
$s has {{ $s | len }} elements <br>

$s has 0 elements
$s has 1 elements
$s has 2 elements
$s has 0 elements

Hm. It didn’t here. I did not check for len but had the slice printed out by warnf %#v and that always showed some “residual” elements (for lack of a better description.
Just tried it again and now it works as you said. Interesting. Maybe I did something else before.