11ty comes with some useful plugins for markdown manipulation, one of these is markdown-it-attrs.
This plugin should be used combined with its big brother, the markdown parser markdown-it, which is already added in 11ty basic installation.
markdown-it-attrs uses markdown-it
and add the possibility to add attributes to HTML nodes generated from markdown.
To use it, add this plugin to the .eleventy
configuration file:
- require
markdown-it
const markdownIt = require('markdown-it')
- require
markdown-it-attrs
const markdownItAttrs = require('markdown-it-attrs')
- define basic
markdown-it
configuration options
const markdownItOptions = {
html: true,
breaks: true,
linkify: true
}
- set
markdown-it-attrs
asmarkdown-it
usage options
const markdownLib = markdownIt(markdownItOptions).use(markdownItAttrs)
- set as eleventy configuration the new markdown configuration
eleventyConfig.setLibrary('md', markdownLib)
To sum up:
// .eleventy.js
const markdownIt = require('markdown-it')
const markdownItAttrs = require('markdown-it-attrs')
const markdownItOptions = {
html: true,
breaks: true,
linkify: true
}
const markdownLib = markdownIt(markdownItOptions).use(markdownItAttrs)
eleventyConfig.setLibrary('md', markdownLib)
Example of usage
# This is a title {.c-article-section__title}
This is a paragraph with data-state {data-state=important}
Another text with attributes {.c-article-section__disclaimer #articleId attr=value attr2="spaced value"}
![Alt text](image.jpg){.u-shadow}
[Link in a new tab](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a){target="_blank" rel="noopener"}
will output
<h1 class="c-article-section__title">This is a title</h1>
<p data-state=important>This is a paragraph with data-state</p>
<p class="c-article-section__disclaimer" id="articleId" attr=value attr2="spaced value">Another text with attributes</p>
<img class="u-shadow" src="image.jpg" alt="Alt text">
<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a" target="_blank" rel="noopener">Link in a new tab</a>
๐งจ !important
Note the last line where I added the
target="_blank"
attribute to the link to open it in a new browser tab. It's ok open a link in a new tab, but for security reasons it has to have also therel="noopener"
attribute.
Side note: unfortunately, I did not find a way to add attributes to markdown tables and blockquote ๐ข
๐ More info
Top comments (4)
I think you forgot .u-shadow class in the image tag in the output right?
Thank you Joren! ๐ I just noticed that I also forgot to add the ALT text in the output ๐ I have just fixed both. Have a nice day!
Thank you :) cool tips btw, we are using 11ty and actually were wondering if there was an easy way to change how markup is spit out from the markdown, mostly adding classes, so we can style our content better. This helps!
it doesn't work for me