Search code examples
rubyjekyll

Loop over CSV rows in jekyll


I'm encountering some issues with loading data from a csv file with jekyll. I've made some custom collections using the following _config.yml seup:

collections_dir: collections

collections:
  people:
    output: true
  publications:
    output: true

Now I this is what my structure looks like (just showing the relevant parts):

.
├── collections
│   ├── _people
│   │   ├── x.md
│   │   ├── y.md
│   └── _publications
│       └── data.csv
├── index.html
└── _config.yml

When I try to loop over my collections using this link as a guide it doesn't seem to work

# except from my index.html file
{% for row in site.publications.data %}
    <p>name: {{row.name}}</p>
{% endfor %}

Solution

  • I think you are after a data file, rather than a collection here. The main differences are:

    • Data files can have each item as entries in a single file, or separate files in a subfolder of _data
    • Collections have each item as a separate file only
    • Data entries do not output a page per entry
    • Collections can output a page per entry

    Here's how you would change this to data:

    1. Move collections/publications/data.csv to _data/publications.csv

    2. Remove the publications entry from collections in _config.yml

    3. Change your loop to the following:

      {% for row in site.data.publications %}
        <p>name: {{ row.name }}</p>
      {% endfor %}
      

    If you want to use a data file and output a page per entry, a popular plugin to do so is https://github.com/avillafiorita/jekyll-datapage_gen

    Alternatively, you could split the CSV into separate Markdown files and use a collection to avoid adding a plugin.