eleventy
eleventy copied to clipboard
Access eleventy configuration in shortcodes
Some shortcodes would greatly benefits from accessing eleventy configuration, like eleventy-img
with pathprefix
.
In the same way we could access page.data
in shortcodes, exposing a this.config
could help tweak shortcode depending on the global configuration of Eleventy.
At the moment, this can be achieved by bypassing CLI configuration with env
variables and settings everything in the JS. Providing a clean way to access config would be more straightforward.
Workaround example:
const Path = require('path');
const fs = require("fs");
const Image = require('@11ty/eleventy-img');
module.exports = function(eleventyConfig) {
const pathPrefix = process.env.PATH_PREFIX || '/';
eleventyConfig.addNunjucksShortcode("image", (src, alt, sizes, classes, widths) => {
const options = {
widths: widths ? widths.split(' ').map(s => parseInt(s, 10)) : [300],
formats: ["webp"],
outputDir: '_site/img',
urlPath: pathPrefix + 'img/'
};
Image(src, options);
const metadata = Image.statsSync(src, options);
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
class: `img-fluid ${classes || ''}`
};
return Image.generateHTML(metadata, imageAttributes);
})
return {
pathPrefix
};
};
I think there is a lot of pieces to this request but just to loop the pathprefix point together:
The new HTML <base>
plugin solves the path prefixing feature in a much cleaner way: https://www.11ty.dev/docs/plugins/html-base/ and won’t require any plugin changes to apply path prefix throughout your project