2
votes

Following the Jekyll Docs, I have developed a people.yml file:

johnsmith:
  name: John Smith
  title: Director
  image: img/johnsmith.jpg

janedoe:
  name: Jane Doe
  title: Coordinator
  image: img/janedoe.jpg

If I loop through people...

{% for person in site.data.people %}
  <p>{{ person }}</p>
{% endfor %}

... I get these outputs:

johnsmith{"name"=>"John Smith", "title"=>"Director", "image"=>"img/johnsmith.jpg"}
janedoe{"name"=>"Jane Doe", "title"=>"Coordinator", "image"=>"img/janedoe.jpg"}

However, when I try to access just one member from the yaml file...

{% assign person = site.data.people['janedoe'] %}

... I get a slightly different version of the data:

{"name"=>"Jane Doe", "title"=>"Coordinator", "image"=>"img/janedoe.jpg"}

I took this information, and I set out to make a person-card.html include:

<div>
  <img src="{{ person[1].image }}" alt="{{ person[1].name }}">
</div>
<div>
  <p>{{ person[1].name }}</p>
  <p>{{ person[1].title }}</p>
</div>

On a page with a loop that accesses the data file, it works. On the contrary, if I use it with a person passed in from front matter, it does not work because the indexes have to be removed. Changing it to this works:

---
layout: default
person: janedoe
---
{% assign person = site.data.people[page.person] %}
<div>
  <img src="{{ person.image }}" alt="{{ person.name }}">
</div>
<div>
  <p>{{ person.name }}</p>
  <p>{{ person.title }}</p>
</div>

My question - given the people.yml file above, how can I make a reusable include that works in either a for loop or with a single record from people.yml passed in through front matter as in the examples above?

1

1 Answers

1
votes

The loop :

{% for people in site.data.people %}
    {% assign person = people[1] %}
    {% include person-card.html %}
{% endfor %}

Note we just assign the useful part (people[1]) to person.

The _includes/person-card.html include :

<div>
  <img src="{{ person.image }}" alt="{{ person.name }}">
</div>
<div>
  <p>{{ person.name }}</p>
  <p>{{ person.title }}</p>
</div>

Jane's page :

---
layout: person
person: janedoe
---

The _layouts/person.html layout :

---
layout: default
---
{% assign person = site.data.people[page.person] %}
{% include person-card.html %}