How to select array element by element property

I’ve spent an hour trying to do something so simple and need help, thank you in advance.

Given this Data file.

data/eleders.yml

elders:
  - elder_id: steve
    name: Steve Smith

  - elder_id: john
    name: John Smith

In my template, where .Params.elder_id = “steve”

{{ $elder := index .Site.Data.elders .Params.elder_id  }}

$elder contains the entire array and not the expected single map object with elder_id = “steve”.

map[elders:[map[elder_id:steve name:Steve Smith] map[elder_id:john name:John Smith]]]

Can someone please help me understand how to select an array element (object) by key?

Thank you so much,

Karl

It finally came to me that this was an array of maps.

I’m using range first 1 to access the array and I know it will only return one array map.

{{ define "main" }}
{{ $data := index .Site.Data.elders }}
<section class="container bg-containerBackground py-5 prose md:prose-md px-3">
    {{ range first 1 (where $data.elders "id" .Params.elder_id) }}
    <p>{{ .id }}</p>
    {{ end }}
</section>
{{ end }}

Hope this helps someone.

Hugo newbie…

Also note that the data file is the highest level object. Currently you have to use .Site.Data.elders.elders to get to the data. Do this instead:

data/elders.yml

- elder_id: steve
  name: Steve Smith
- elder_id: john
  name: John Smith

Also note that using elder_id in a data file named elders is redundant. Simplify:

- id: steve
  name: Steve Smith
- id: john
  name: John Smith
4 Likes

Thank you for the tip! Learning more every day!

1 Like

Further improvement

data/elders.yml

- id: steve
  name: Steve Smith

- id: john
  name: John Smith
  • $allElders - the Data file elders.yml array
  • $elders - is a single element array of a map
  • $elder - is the map of the desired elder element. Defining a variable at the top of the template provides access to the data within the template.
  • .Params.elder_id - page variable that contains the elder_id for this chapter.

Note: this reason for the separate elder.yml file is that elder data is read from multiple pages and partial templates and I wanted to keep all elder data in a single file because the end-users will be using Forestry.IO to edit their site content and data files.

{{ define "main" }}
{{ $allElders := index .Site.Data.elders }}
{{ $elders := where $allElders "id" .Params.elder_id }}
{{ $elder := index $elders 0 }}

 <section class="container bg-containerBackground py-5 prose md:prose-md px-3">
     <p>{{ $elder.id }}</p>
 </section>
 {{ end }}

Hope this helps someone, I’m learning a lot today!

Karl

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