Accessing Specific Items From Data Files In Jekyll

Published:
Last modified:

Overview

Having a sample data file, we explore some of the options we have to access a specific item.

For the data file projects.yml located in /_data/projects.yml:

- project: funtime
  url: www.funtime.url
  description: This is really fun

- project: supertime
  url: www.supertime.url
  description: This is really super

How can we access the data item whose project name is funtime?

Using an index

If we know the data item index, we can access them directly, in this case it is located in the position “0”:

{{site.data.projects[0]}}

Output:

    {ā€œprojectā€=>ā€funtimeā€, ā€œurlā€=>ā€www.funtime.urlā€,ā€œdescriptionā€=>ā€This is really funā€}

Iterating

Iterating through all the data looking for an attribute

{% for item in site.data.projects %}
    {% if item.project == "funtime" %}
    {{item}}
    {% endif %}
{% endfor %}

Outputs:

{ā€œprojectā€=>ā€funtimeā€, ā€œurlā€=>ā€www.funtime.urlā€, ā€œdescriptionā€=>ā€This is really funā€}

Changing the data file

The above data file can be optimized to make it more elegant and use the project name as their key:

funtime:
  url: www.funtime.url
  description: This is really fun

supertime:
  url: www.supertime.url
  description: This is really super

This way we can access each of the items directly:

{{site.data.projects['funtime']}}

So it would output:

{ā€œurlā€=>ā€www.funtime.urlā€, ā€œdescriptionā€=>ā€This is really funā€}
Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


Accessing Specific Data Items from files in Jekyll's _data directory

Clutter-free software concepts.
Translations English EspaƱol

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·