Automatically open external links in a new tab in Eleventy 3
Although some frown on the practice, I prefer to have external links open in a new tab. I use Eleventy 3 for this site and write my blog posts in Markdown. I want to be able to easily add the target="_blank"
attribute to external links in my Markdown files.
I started with markdown-it-attrs
which is very useful, but for some reason it failed with links. I then found markdown-it-link-attributes
which turned out be the best solution for my purposes.
markdown-it-attrs
Eleventy uses the markdown-it
parser which we can extend with other plugins. I first added markdown-it-attrs
, which enables easy adding of classes and other attributes in Markdown.
For example, we can have this in our Markdown file:
# This is a header {.style-me}
This is a paragraph {data-toggle=modal}
And the HTML output is this:
<h1 class="style-me">This is a header</h1>
<p data-toggle="modal">This is a paragraph</p>
To add this feature in Eleventy 3, we install the npm package in our project:
npm install --save-dev markdown-it-attrs
Then add it in our eleventy.config.sys
file:
// eleventy.config.sys
import markdownItAttrs from "markdown-it-attrs";
export default async function (eleventyConfig) {
...
// markdown-it-attrs
eleventyConfig.amendLibrary("md", (mdLib) => mdLib.use(markdownItAttrs));
...
};
This works beautifully in most cases and is very handy to have, but unfortunately it failed with links -- which was my original reason for installing it in the first place!
Link fail
For me at least, markdown-it-attrs
failed with links. Maybe I am missing something. When given this Markdown:
Here is a [Link to Eleventy](https://www.11ty.dev/){target="\_blank"}
The HTML output was:
<p>
Here is a
<a href="https://www.11ty.dev/">Link to 11ty</a> {target="_blank"}
</p>
The solution: markdown-it-link-attributes
In searching for a solution, I came across markdown-it-link-attributes
, which works perfectly for my purposes.
- ← Previous
This is my fourth post - Next →
Use LightningCSS with Eleventy 3