Creating link tags with a data file and Nunjucks, using Eleventy

In order to keep site-specific data separate from my templates I've put together a little something something to achieve that.

Published

Category

  • nunjucks
  • 11ty

I've been putting together my own Eleventy template to use in future projects. As with any template I want to keep all data separate from the template itself. With Eleventy this is simply handled through Eleventy global data files. A typical use case is to create a JSON or JS file in your data directory and use that to add information like site name, description, etc etc which can simply be referenced in your template.

For a bunch of my projects I have various link tags in the head of my HTML, some to cater for identity (like rel=me or rel=pgpkey), some for prefetching domain names (like rel=dns-prefetch), you get the jist. All this stuff clearly is data which should be separate from the template and as link tags follow the same structure I put together a little loop to achieve this.

I have a data file called site.js and a bunch of objects in an array called links:

module.exports = {
links: [
{
rel: 'dns-prefetch',
url: 'https://website.com',
},
{
rel: 'me',
url: 'https://website.com',
},
{
rel: 'pgpkey',
url: '123456789',
},
],
};

And in my base Nunjucks template I have something like this:

<html lang='en'>
<head>
{% if site.links %} {% for item in site.links %}
<link rel='{{item.rel}}' href='{{item.url}}' />
{% endfor %} {% endif %}
</head>
</html>

This loop looks for a reference to links in the site data file and if it doesn't exist then it doesn't render anything. If there is a links reference it will loop through each one creating a link tag with the relevant rel and url values for each.

Anyway, a very simple use case and you could probably expand this further and generate any link tag using data, but at the moment this works for my needs.