Create a JSON feed with 11ty


Eleventy is great because you can literally output anything. To output a JSON feed with 11ty, all you need to do is create a file called feed.njk and adding the following to it:

Code language
text
---
permalink: '/my-cool-feed.json'
---
{
  "posts": [
    {% for item in collections.posts %}
      {
        "title": "{{ item.data.title }}",
        "url": "{{ item.url }}"
      }{% if not loop.last %},{% endif %}
    {% endfor %}
  ]
}

This example is using Nunjucks, which you can find documentation for here.

We use the loop.last variable to only add a comma at the end of items that aren’t the last item.

The JSON feed will give you an output like this:

Code language
json
{
  "posts": [
    {
      "title": "Quick and simple image placeholder",
      "url": "/posts/quick-and-simple-image-placeholder/"
    },
    {
      "title": "Color Palette Generator",
      "url": "/posts/color-palette-generator/"
    }
  ]
}

This little snippet creates a feed of posts that have a title and url. Whatever data you have access to in your collection, you can output in this feed, too.

Pro tip: Make sure you set the permalink to have a .json extension so the browser knows that it is application/json. That’ll save you a lot of server hassle!

You can grab a basic Eleventy starter for this demo here.


Comments

If you liked this post, you might like these ones, too

  1. Use CSS Clamp to create a more flexible wrapper utility

    A handy way to use modern CSS functions to give yourself fine-grained, yet flexible, design control.

    Continue
  2. Aligning description lists with CSS Grid

    🔥 A handy quick tip.

    Continue
  3. Use grayscale filter to see where you are relying too much on colour

    🔥 A handy quick tip.

    Continue

Become a supporter by joining the Piccalilli Membership

For $5 per month, you get access to a private, friendly Discord community, a regular newsletter, huge discounts on courses and free access to all premium tutorials.

Most importantly, by becoming a supporter, you help make as much content, free-to-everyone as possible on this site, which benefits everyone. As a member, you also get an ad-free experience around the site.

Support Piccalilli by becoming a member

Sign up for updates

Stay up to date with updates from Piccalilli. You’ll get alerted as soon as any new content gets published. You’ll also get updates on upcoming courses and membership features! You can unsubscribe at any time, too.