DEV Community

loading...

Add HTML classes to 11ty markdown content

giulia_chiola profile image Giulia Chiola Originally published at giuliachiola.dev Updated on ・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')
Enter fullscreen mode Exit fullscreen mode
  • require markdown-it-attrs
const markdownItAttrs = require('markdown-it-attrs')
Enter fullscreen mode Exit fullscreen mode
  • define basic markdown-it configuration options
const markdownItOptions = {
  html: true,
  breaks: true,
  linkify: true
}
Enter fullscreen mode Exit fullscreen mode
  • set markdown-it-attrs as markdown-it usage options
const markdownLib = markdownIt(markdownItOptions).use(markdownItAttrs)
Enter fullscreen mode Exit fullscreen mode
  • set as eleventy configuration the new markdown configuration
eleventyConfig.setLibrary('md', markdownLib)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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"}
Enter fullscreen mode Exit fullscreen mode

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 src="image.jpg">
<a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a" target="_blank" rel="noopener">Link in a new tab</a>
Enter fullscreen mode Exit fullscreen mode

🧨 !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

Discussion (0)

pic
Editor guide