Hierarchical Data

Hi, Everyone.

I know it’s possible to pull in data from a file such as data/people.yml:

friends:
  - Bill
  - Bob
  - Mary

But, I am wondering if there is a way to pull in hierarchical data, such as data/people.yml:

friends:
  - Bob
    - Smith
    - 1101 W. River Rd.
    - March 3, 1966
  - Mary
    - Johnson
    - 100 State St.
    - June 18, 1967

For example, how would I access Bob Smith’s birthday (March 3, 1996) in the above example?

Any thoughts will be most appreciated!

– Clint (clint@auditpad.com)

1 Like

The only limitation I think is for the Yaml syntax to be valid, and for practicality to have a sensible data tree.

Here, your problem is that your syntax is invalid because one can’t nest an array [Smith, 1101…, 1966-03-03] under a string “Bob”. I see two approaches:

friends:
  bob:
    name: Bob Smith
    address: 101 Foo Lane
    birth: 1966-03-03
  mary:
    name: Mary Johnson
    address: 120 Bar St
    birth: 1967-06-18

Where the keys (bob, mary) have to be unique (think usernames). You could then do data.friends[username]. Or you could simply think of them as an array of records:

friends:
  -
    name: Bob Smith
    address: 101 Foo Lane
    birth: 1966-03-03
  -
    name: Mary Johnson
    address: 120 Bar St
    birth: 1967-06-18

Where this time you have to filter the records when you want to find a particular one or just go through them all with Array#each. I’d go with the former.

That worked exactly as I wanted! Thanks jollard. Here’s what I used:

data/people.yml:

friends:
  -
    name: Bob Smith
    address: 101 Foo Lane
    birth: 1966-03-03
  -
    name: Mary Johnson
    address: 120 Bar St
    birth: 1967-06-18

source/index.html:

<h1>Friends</h1>
<% data.people.friends.each do |f| %>
<%= f.name %><br/>
<%= f.address %><br/>
<%= f.birth %><br/><br/>
<% end %>

And, here is the output:

<h1>Friends</h1>
Bob Smith<br/>
101 Foo Lane<br/>
1966-03-03<br/><br/>
Mary Johnson<br/>
120 Bar St<br/>
1967-06-18<br/><br/>
1 Like

I’m reviving this thread.

I’m new to Middleman and Ruby both.

How would you create a two separate pages for Bob and Mary from the above datafile

If a user goes to middleman/people/bob.html. How can I pull bob’s info and populate the page?