Data from yaml files in 11ty / eleventy
Asked Answered
W

1

6

On my 11ty site (skeleventy-starter) I want to parse hundreds of reviews. These reviews are stored in my data folder in a folder called reviews as individual yaml-files (named like this: "entry-7128372832.yml"). Each yaml file looks like this:

_id: 84494a00-b086-11ea-94d5-7f955bef1b4e
rating: 5
name: Name
review: "review body"
date: "2019-05-12T12:12:31.116Z"

I added the custom data file format to the 11ty config as stated in the documentation:

const yaml = require("js-yaml");

module.exports = (eleventyConfig) => {
  
// Yaml
 eleventyConfig.addDataExtension("yaml", (contents) =>
        yaml.safeLoad(contents)
 );
};

However, when I try to loop over the review-data in my .njk-files:

{% for review in reviews %}
    <p>{{ review.name }}</p>
    <p>{{ review.rating }}</p>
    <p>{{ review.review }}</p>
{% endfor %}

I neither seem to have access to the data nor get an error in the console. What am I missing here? Any help is appreciated. Thanks!

Wilden answered 29/6, 2020 at 13:21 Comment(0)
G
4

You need to change the file extensions for all of the _data/entry-*.yml files to use the .yaml extension (note the additional a).

The official file extension recommended by the YAML team is .yaml; however, .yml is also common out in the wild (see this SO question for a quick dive).

The code sample for YAML support in the Custom Data File Format docs is written to support the official .yaml extension.

In this line of your 11ty config "yaml" represents a literal file extension to support, not just the name of the colloquial name of the language:

eleventyConfig.addDataExtension("yaml", (contents) =>

If you want to expose both .yml and .yaml files in your _data/ directory, this will work:

eleventyConfig.addDataExtension('yaml', contents => yaml.safeLoad(contents))
eleventyConfig.addDataExtension('yml', contents => yaml.safeLoad(contents))

Note that the order of code above affects the 11ty Data Cascade. If there were a priority clash between a .yaml and a .yml file, .yml would win because the extension is added later.

Also important: 11ty just recently added YAML support in v0.10.0, so be sure you are at version 0.10.0 or higher.

Glacis answered 2/7, 2020 at 2:32 Comment(4)
Thank you so much! That was the solution. I also want to point out that if you want to loop over a directory of files you need to do it like this {% for key, val in subdata %} {{ key }} {% endfor %} github.com/11ty/eleventy/issues/304#issuecomment-440678396Wilden
Awesome! This got me too, i have .yml in muscle memory for some reason :)Glacis
What do you mean by "default YAML support"? The Eleventy documentation still writes about using require("js-yaml") and addDataExtension.Steffin
@AlexVang I read that again - no idea why "default" was in there. Probably too much caffeine. I meant to say that support for YAML was recently added. Edited my answer.Glacis

© 2022 - 2024 — McMap. All rights reserved.