Search code examples
nunjuckseleventy

11ty multiple data sources for one template


I'm using 11ty to build static web pages. I am creating data sources as json files and storing them in the globally accessible _data directory.

template.njk
{% for key, value in data %}
    <div>
        <span class="text-4xl">{{key}}</span>

        <ul>
           {% for item in value %}
            <li>{{ item.country }}</li>
           {% endfor %}
        </ul>
    </div>
{% endfor %}
_data
    data_source_1.json
    data_source_2.json
    data_source_3.json

I don't want to have 3 templates. I just want one template. How do I pass each data source as a variable to the template?


Solution

  • 11ty is different from the JavaScript frameworks/libraries around. You don't need to "bring in" all your data on each template if multiple sources. It can be done trough Collections or global _data files in the "create once, use anywhere" style.

    Check that short EggHead video about creating pages (and the collection) from _data pages: https://egghead.io/lessons/11ty-generate-eleventy-11ty-pages-from-external-data

    Its like the basic example from the docs with the possums array, but the addAllPagesToCollections: true line in the front matter will create the globally usable collection.

    Say you add another template to display a single element from _data source and add all to collections, in a books.njk template... Then on any page without "bringing in data in the front matter" you can:

    {% for book in collections.books %}
      ## [ {{ book.data.title }} ]( {{ book.url }} )
    {% endfor %}
    

    ...that way you can have as much different "data sources" collections on a single page. There are for sure more to say on the subject but hope it helped and pointed you in the direction to digg in the docs & online in general.

    Edit:

    Depending on your data and if no individual pages are needed, you can also store your global _data pages directly in .json and loop trough them without creating a collection.

    _data/family.json

    {
      "possums":[
        {
            "name": "Fluffy",
            "age": 2
          },
          {
            "name": "Sparky",
            "age": 3
          },
          {
            "name": "Boby",
            "age": 1
          }
      ]
    }
    

    someTemplate.md

    {% for possum in family.possums %}
      {{ possum.name }} is {{possum.age}} years old
    {% endfor %}
    

    Storing _data files as .js is also possible by exporting, but the simplest way for small bits of data can be the.json way.

    Most of time you'll have a _data/website.json file, with global data like "name, tagline, whatever".