Splitting array into subarrays of n components each

I am trying to take an array of 6 elements and split into 2 nested arrays of 3 elements each

  images:
    - url: "images/carousel-1.svg"
    - url: "images/carousel-2.svg"
    - url: "images/carousel-3.svg"
    - url: "images/carousel-4.svg"
    - url: "images/carousel-5.svg"
    - url: "images/carousel-6.svg"
[map[[map[url:images/carousel-1.svg] map[url:images/carousel-2.svg] map[url:images/carousel-3.svg]]
map[[map[url:images/carousel-4.svg] map[url:images/carousel-5.svg] map[url:images/carousel-6.svg]]]

I want to write a template like this:

{{ range $array }}
<div>
{{ range . }}
<img src={{ . }}>
{{ end }}
</div>
{{ end }}

Is there anything available to make this possible? It seems similar to .Paginatior, but with an array and not pages:

{{ range (.Paginator 5).Pages }}

Create a partial:

layouts/partials/convert-slice-to-slice-of-slices.html
{{ $r := slice (first .n .s) }}

{{ $t := slice }}
{{ range $k, $_ := .s | after .n }}
  {{ $t = $t | append . }}
  {{ if or (math.ModBool (add $k 1) $.n) (eq (add $k $.n 1) (len $.s)) }}
    {{ $r = $r | append $t }}
    {{ $t = slice }}
  {{ end }}
{{ end }}

{{ return $r }}

Then call it with:

{{ $s := slice "a" "b" "c" "d" "e" "f" }}
{{ $result := partial "convert-slice-to-slice-of-slices.html" (dict "s" $s "n" 3) }}
<pre>{{ jsonify (dict "indent" "  ") $result }}</pre>

Any leftovers are appended in a final slice, which may have length less than n.

To change the number of elements per nested slice, change n.

1 Like

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