Generating Jekyll pages from a folder of JSON

Viewed 326

So I have a bunch of cocktail recipes in a folder, each with a distinct name like screwdriver.json or adult-hot-chocolate.json with a correspondingly named image, and each recipe looks like this:

{
"name": "Adult Hot Chocolate",
"description": "Appropriately named 'adult hot chocolate', this recipe is one of the easiest and most common ways to spike your cocoa. To make it, you will simply add a shot of peppermint schnapps to your favorite hot chocolate and a delicious, warm drink is yours to enjoy.",
"github": "thesanjeevsharma",
"ingredients": [
    {
        "quantity": "2",
        "measure": "oz",
        "ingredient": "Peppermint Schnapps"
    },
    {
        "quantity": "6",
        "measure": "oz",
        "ingredient": "Hot Chocolate"
    },
    {
        "quantity": "",
        "measure": "",
        "ingredient": "Garnish: ​whipped cream"
    },
    {
        "quantity": "",
        "measure": "",
        "ingredient": "Garnish: chocolate sprinkles or shaved chocolate"
    }
],
"directions": [
    "Gather the ingredients.",
    "Pour the schnapps into a warm mug or Irish coffee glass.",
    "Fill with hot chocolate.",
    "Stir well.",
    "Optionally, top with whipped cream and chocolate sprinkles or shaved chocolate.",
    "Serve and enjoy!"
],
"image": "adult-hot-chocolate.jpg",
"keywords": [
    "chocolate",
    "peppermint",
    "schnapps"
]
}

I want to create a layout and randomly pick one recipe and image to show on my website. I know how to do it if they were all just in one big YAML document, but it’s not clear to me how to tell Jekyll to parse separate files so I can reference one at random.

The other possibility is to combine them into one big json but then I couldn’t just pull down new recipes as easily from the original source.

Any help would be greatly appreciated!

1 Answers

Please have a look to the jekyll data documentation.

So you have to create a _data folder, when it is not already there.

Then copy per cocktail a json file iinside the sub-folder e.g. _data/cocktails.

To read the list of cocktails you have to create page with html or markdown content.

The content of the html could be something like this

---
layout: default
title: "My Cocktails"
---

<ul>
{% for file in site.data.cocktails%}
{% assign cocktail = file[1] %} {% comment %}The assign is needed, because we have different json files!{% endcomment %}
  <li><strong>{{ cocktail.name }}</strong> - {{ cocktail.description}}</li>
{% endfor %}
</ul>

Related