Search code examples
eleventy

How to add taxonomies in 11ty?


I'd like to use a json-file that looks somewhat like this

[{
    "id": "foo",
    "url": "video",
    "topic": "Fancy foos"},
 {
    "id": "bars",
    "url": "video",
    "topic": "Naughty bars"
}]

as a source for several overview pages that group the entries by topic (I guess it's called taxonomy). What would be a good solution for this? Parse the json, group it with js and create a custom collection for each topic? If so, where would this belong, to a file in the _data folder?

Thx in advance!


Solution

  • I'm not 100% sure I get what you intend, but let me try to help. First, yes, store the file in your _data folder. Let's assume you call it taxonomies.json. This means your code has access to the array as taxonomies.

    Next, if you want to build pages based on this data, look at the docs for Create Pages from Data, which describe how to dynamically generate pages based on your data. You could have one per taxonomy. For ex:

    ---
    pagination:
        data: taxonomies
        size: 1
        alias: tax
    permalink: "topic/{{ tax.id | slug }}/"
    ---
    
    content here
    

    Your content needs to be driven by the current taxonomy. I assume you will have a kind of content, like posts, that include a taxonomy? If so, you can create a short code or filter that scans all posts and returns the one with a particular taxonomy in the front data. For example, here's how I get posts that match a category:

    {% assign posts = collections.posts | getByCategory: cat %}
    

    And getByCategory is defined in .eleventy.js. The particulars of this part are really dependent on what content you are trying to show.