Hello! I am new to Hugo and trying it out to build my simple photography blog. On the homepage, I would like to render a simple masonry layout with 50 images or so. I have the following shortcode here running and rendering the images just fine:
/layouts/shortcodes/homepage-masonry.html
<div class="masonry">
{{ $path := print "images/homepage" }}
{{ range sort (readDir (delimit (slice "static" $path) "/")) "Name" "asc" }}
{{ if (findRE ".jpg$" .Name) }}
{{ $src := print "/images/homepage/" .Name }}
<img src="{{ $src }}" />
{{ end }}
{{ end }}
</div>
In my static/images/homepage folder, I have the image file names set to JSA_1.jpg, JSA_2.jpg … etc all the way to JSA_50.jpg. In my macOS folder view, when sorted ASC by file name, I clearly get the sort I expect - _1 to _50.jpg. However when this page loads, I’m getting a very weird order:
JSA_1, JSA_10, _100, _101 … all the way to _109 then I get _11 … then _111 through _119 then _12
It doesn’t really make sense, and I hope I’m missing something very obvious here.
Hi, there might be some other solution, but as a workaround you could prefix the one- and two-digit numbers with zeros, like JSA_001, and so on. Some sorting algorithms prefer it that way.
Try this solution out: Order pages by the id
As for why: you are sorting strings; “A1” < “A1000” < “A2”.
Thank you for the link! Using that, I was able to get it working with this solution:
{{ $s := slice 0 }}
{{ $path := print "images/homepage" }}
{{ range $index, $element := (sort (readDir (delimit (slice "static" $path) "/")) "Name" "asc") }}
{{ if (findRE ".jpg$" .Name) }}
{{ $src := print "/images/homepage/" .Name }}
{{ $s = $s | append (int (strings.TrimSuffix ".jpg" (slicestr .Name 1) )) }}
{{ end }}
{{ end }}
<div class="masonry">
{{ range $index, $element := (after 1 (sort $s)) }}
{{ $c := add $index 1 }}
{{ $src := print "/images/homepage/0" $c ".jpg" }}
<img src="{{ $src }}" />
{{ end }}
</div>
NOTE: My images are in the static/images/homepage folder and I have their names prefixed with 0 and then going 1-50.jpg.
Thanks for the suggestion! I tried this, however Hugo still didn’t like it and the sort was messed up. I posted the solution below.