I'm using markdown reference links in my eleventy site.
Rather than repeatedly defining links on each page, I'd rather put them in one place, and just reference them in my pages.
For example links.md
could contain:
[github]: <https://github.com/>
[stackoverflow]: <https://stackoverflow.com/>
And then any page could reference these links.
Anyone know if this is possible?
If you want to define the links in one spot and access them globally in your templates, you can create a global data file in the _data/*
directory containing link definitions and then reference them in your Markdown files. Below is an example global data file _data/links.json
:
{
"socials": {
"github": "<https://github.com/>",
"stackoverflow": "<https://stackoverflow.com/>",
"twitter": "<https://twitter.com/>",
...
}
}
This way you can access the data in _data/links.json
containing link definitions globally throughout your 11ty project using interpolation like {{ foo }}
. Where if you want to use that global data in templates, you reference the name of the global data file links
and then access object keys as necessary for example {{ links.socials.key }}
.
Unfortunately using [GitHub]({{ links.socials.github }})
won't work, but to avoid adding link definitions on each page you could always do something like:
---
title: Some title
templateEngineOverride: njk, md
---
<a href="{{ links.socials.github }}">GitHub</a>
Or if using Nunjucks as your templating engine, you could create variables for your social links using set
and avoid defining Markdown reference links.
---
title: Some title
---
{% set github = links.socials.github %}
[Link to my GitHub]({{ github }})
Lastly, using a shortcode wouldn't be a bad idea paired with the global data.
module.exports = function(eleventyConfig) {
eleventyConfig.addShortCode("socialLink", function(linkName, url) {
return `<a href="${url}">${linkName}</a>`;
});
}
// Template Usage (.md or .njk etc)
{% socialLink "GitHub", links.socials.github %}
// outputs: <a href="<https://github.com>">GitHub</a>