Range over array in order specified in front matter array

I have the following code:

  name = "a"
  name = "b"
  name = "c"
  name = "f"

names = ["f", "a", "b"]

{{$y := (.GetPage (print "/cards/_index.md")).Params.cards.item}}

{{$x := where $y ".name" "in" .Params.names}}

I want to check what .Params.names are specified in cards.item and return the values that are found. The code works and returns: a, b, f.

But I’d like the code to return the values in the order specified in .Params.names so f, a, b

How would I do this? Thanks.

{{ $a := slice
  (dict "name" "a")
  (dict "name" "b")
  (dict "name" "c")
  (dict "name" "f")

{{ $b := slice "f" "a" "b" }}

{{ $c := slice }}
{{ range $b }}
  {{ $c = $c | append (where $a "name" .) }}
{{ end }}

<pre>{{- jsonify (dict "indent" "  ") $c -}}</pre>
1 Like

@jmooring isn’t intersect what the Golang gods invented for this?

I tried using intersect but could not get it to work. Perhaps it’s because I have a map and an array, whereas with intersect both need to be arrays? Not sure.

Yes, I would range through your data structure and create an array (slice) from that. Then compare via intersect with the frontmatter.

1 Like

Please post tested code. I couldn’t figure out a more elegant way to return this slice:

    "name": "f"
    "name": "a"
    "name": "b"

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