Add HTML classes to 11ty markdown content

Β·

2 min read

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 as markdown-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 the rel="noopener" attribute.

Side note: unfortunately, I did not find a way to add attributes to markdown tables and blockquote 😒

πŸ“š More info