Append to an array within a range loop

Assuming I have a directory with the following images, I would like to get size part of the filenames after the last dash, for the contact- images only, in an array.

The final result would be ["1440w", "1600w", "768w"].

blog-980w.jpg
blog-600w.jpg
contact-1440w.jpg
contact-1600w.jpg
contact-768w.jpg

In the code below, I am succeeding in only matching the contact filenames, and getting the size part out of them, but when I try and append them to the $sizes, the array just resets, and so it only ever contains the most recently appended item.

I am also trying to create an empty array at the beginning, using {{ $sizes := slice}} which seems obviously wrong- is there a better way of doing that?

How can I build the array as I loop through the filenames?

{{ $sizes := slice}} // Create an empty array
{{ $files := (readDir "/images/" )}}
{{ range $files}}
	{{ $parts := ( split .Name "-" )}}
	{{ $generic_part := (delimit (first (sub (len ( split .Name "-" )) 1) ( split .Name "-" )) "-") }}
	{{ if (eq (string $generic_part) "contact" ) }}
		{{ $last_part := (index (last 1 $parts) 0)}}
		{{ $size_part := index ( split $last_part "." ) 0 }} // This gets the part of the file name I need
		{{ $sizes := $sizes | append $size_part }} // This resets the $sizes variable.
	{{ end }}
{{ end }}

Try = (ie not :=) :

{{ $sizes = $sizes | append $size_part }}
3 Likes

Using = instead of := to update the solved it.