Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Global Data in 11ty

Using Global Data in 11ty

Any filename you put under _data directory will be globally available to all templates

A template might start with some yaml front matter to give it some local fontmatter data like this:

title: "First post"
author: Kyle
tags: [Post, Intro]

Let's say you wanted to keep author metadata stored elsewhere, you could put that in a global data file _data/authorlist.json like this:

[ "kyle", "brian" ]

Note make sure the filename is globally unique - the data will be available everywhere under authorlist so try to prevent naming collisions

11ty will merge all data together that's available to the template, so when you're building your page, the following information is available:

{
  // local data
  title: "First post",
  author: "Kyle",
  tags: ["Post", "Intro"],
  
  // global data
  authors: [ "kyle", "brian" ]
}

So let's explore two different strategies of how to store data and what it looks like to consume it

Data as Array

[
  {"name": "Kyle", "description": "Likes .NET Development, JavaScript, and Cats"},
  {"name": "Brian", "description": "Automation champion, pottery hobbyist, and volleyball enthusiast"}
]

To make a list of author pages, we can just loop through the list with {% for author in authorlist %} inside a nunjucks template like this:

<ol class="authorlist">

  {% for author in authorlist %}
    <li class="author">
      <a href="/authors/{{author.name}}"> {{ author.name }} </a>
      {{ author.description }}
    </li>
  {% endfor %}
  
</ol>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.