11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17.21k stars 493 forks source link

How to add IDs for headings #812

Closed shadeed closed 4 years ago

shadeed commented 4 years ago

Hello,

Thanks for this great tool. I'm new to it and coming from Jekyll background. I'm writing in Markdown and wanted to add an ID to each heading automatically. What's the easiest way to do so? Here is an example:

<h2 id="this-is-a-heading">This is a heading</h2>

Here is my config file:

module.exports = function(eleventyConfig) {
  eleventyConfig.addPassthroughCopy('src/images')
  const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight")
  eleventyConfig.addPlugin(syntaxHighlight);

  let markdownIt = require("markdown-it");
  let options = {
    html: true,
    breaks: true,
    linkify: true
  };

  eleventyConfig.setLibrary("md", markdownIt(options));

  return {
    dir: { input: 'src', output: 'dist', data: '_data' },
    passthroughFileCopy: true
  }
}

Thanks a lot,

shadeed commented 4 years ago

Closed this since I forked https://github.com/11ty/eleventy-base-blog and used it to suit my needs. Thanks @zachleat for the great starter!

svivian commented 4 years ago

For future reference since I just had the same problem, the answer is to use markdown-it-anchor. The part you need from the base blog config is:

const markdownIt = require("markdown-it");
const markdownItAnchor = require("markdown-it-anchor");

module.exports = function(eleventyConfig) {
  /* Markdown Overrides */
  let markdownLibrary = markdownIt({
    html: true,
    breaks: true,
    linkify: true
  }).use(markdownItAnchor, {
    permalink: true,
    permalinkClass: "direct-link",
    permalinkSymbol: "#"
  });
  eleventyConfig.setLibrary("md", markdownLibrary);
};
NickColley commented 2 years ago

If you'd like to do this without generating links in the headings, only the ID attributes you can do:

const markdownIt = require("markdown-it");
const markdownItNamedHeadings = require("markdown-it-named-headings");

const markdownOptions = {
    html: true,
    breaks: true,
    linkify: true
};
const markdownRenderer = markdownIt(markdownOptions).use(markdownItNamedHeadings);

eleventyConfig.setLibrary("md", markdownRenderer);