Skip to content

Latest commit

 

History

History
74 lines (57 loc) · 2.12 KB

File metadata and controls

74 lines (57 loc) · 2.12 KB

Eleventy plugin for custom html transform with DOM API.

This plugin provides custom html post processing with DOM API via LinkeDOM. For example, you can add ids to headings, change url of images, etc.

Motivation

Add the ability to more flexibly transform html when markdown features are not enough.

Installation

npm i @web-alchemy/eleventy-plugin-html-transform

Usage

Include plugin:

const EleventyPluginHtmlTransform = require('@web-alchemy/eleventy-plugin-html-transform');

module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(EleventyPluginHtmlTransform, {
    handler: async ({ content, page }) => {
      return async (/** @type {Window}*/globalEnv) => {
        /* perform your transformations */
      }
    }
  });
}

Plugin receives one option - handler function, that has parameter as object with fields:

Parameters page and content can help you to filter which pages you should transform. In this case handler should return any falsy value.

If transformations should be performed, handler must return function with window parameter, which is used to perform html mutations.

Example:

const EleventyPluginHtmlTransform = require('@web-alchemy/eleventy-plugin-html-transform');

module.exports = function(eleventyConfig) {
  eleventyConfig.addPlugin(EleventyPluginHtmlTransform, {
    handler: async ({ content, page }) => {
      if (!page.inputPath.includes('blog')) {
        return;
      }

      return async (/** @type {Window}*/globalEnv) => {
        const headings = globalEnv.document.querySelectorAll('h2, h3, h4, h5, h6');
        for (const heading of headings) {
          const slug = slugifySomehow(heading.textContent);
          heading.id = slug;
          heading.innerHTML = `
            <a href="#${slug}">
              ${heading.innerHTML}
            </a>
          `
        }
      }
    }
  });

  return {
    dir: {
      input: 'src'
    }
  }
}