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.
Add the ability to more flexibly transform html when markdown features are not enough.
npm i @web-alchemy/eleventy-plugin-html-transform
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:
content
- html string of rendered templatepage
- eleventy page data
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'
}
}
}