Simple sorting of range with key, value variables

I have a pretty simple range, where i get key and value as variables. Problem now, is that instead of changing the order directly in the array, i would like to do it through the code.
Here is the template range code:

        {{ range $bp, $width := .sizes }}
            {{ $bp = (index $bps $bp) }}
            {{ $print := false }}

            {{ if $bp }}
                {{ $print = (printf "(min-width: %vpx) %vpx" $bp $width) }}
            {{ else }}
                {{ $print = (printf "%vpx" $width) }}
            {{ end }}

            {{ $sizesSlice = $sizesSlice | append $print }}
        {{ end }}

Here is .sizes:

               "sizes": {
                    "0": 1920,
                    "1": 2560,
                    "2": 2048,
                    "3": 2200,
                    "4": 2800,
                    "5": 3840
                }

So instead of appending to the slice with 0-5 it should instead be 5-0. Hope it makes sense.

The sort method i cant seem to use when i have they key and value as variables.

You could sort your slice after your range statement:

{{ $sizesSlice = sort $sizesSlice }}

I tried that, but i don’t seem to be able to sort the map in any useful way.

Heres what $sizesSlize currently returns:

[1920px (min-width: 600px) 2560px (min-width: 900px) 2048px (min-width: 1200px) 2200px (min-width: 1600px) 2800px (min-width: 2200px) 3840px]

And i have no idea how to sort on that.

This is what i get instead after i’ve added the sort to $sizesSlice:

[(min-width: 1200px) 2200px (min-width: 1600px) 2800px (min-width: 600px) 2560px (min-width: 900px) 2048px 1920px (min-width: 2200px) 3840px]

I ended up changing my object so that i could sort directly on the key instead:

                "sizes": [
                    { "bp": "0", "width": "1920" },
                    { "bp": "1", "width": "2560" },
                    { "bp": "2", "width": "2048" },
                    { "bp": "3", "width": "2200" },
                    { "bp": "4", "width": "2800" },
                    { "bp": "5", "width": "3840" }
                ]

And the code to:

        {{ range sort .sizes "bp" "desc" }}
            {{ $bp := .bp }}
            {{ $width := .width }}
            {{ $bp = (index $bps $bp) }}
            {{ $print := false }}

            {{ if $bp }}
                {{ $print = (printf "(min-width: %vpx) %vpx" $bp $width) }}
            {{ else }}
                {{ $print = (printf "%vpx" $width) }}
            {{ end }}

            {{ $sizesSlice = $sizesSlice | append $print }}
        {{ end }}
1 Like