Skip to content

Instantly share code, notes, and snippets.

@patrickhlauke
Last active June 26, 2022 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickhlauke/99bb379963225aedde12d35dc70509b0 to your computer and use it in GitHub Desktop.
Save patrickhlauke/99bb379963225aedde12d35dc70509b0 to your computer and use it in GitHub Desktop.
Fragment for `.eleventy.js` for a slightly modified svg shortcode
const fs = require('fs');
module.exports = config => {
/*
Custom svg shortcode to more cleanly include svgs.
Based on https://dev.to/extrabright/11ty-inject-svg-code-using-shortcodes-3l4m but extended to support additional attributes.
Takes file path, and optionally any additional attributes to be output as part of the <svg> opening tag
Basic example:
{% svg "/path/to/file.svg" %}
Examples with attributes:
{% svg "/path/to/file.svg",'role="img" aria-label="TetraLogical"' %}
{% svg "/path/to/file.svg",'class="icon" aria-hidden="true"' %}
*/
config.addShortcode("svg", function (file, attributes) {
let relativeFilePath = `./src/${file}`;
let data = fs.readFileSync(relativeFilePath,
function(err, contents) {
if (err) return err
return contents
}
);
data = data.toString('utf8');
if (attributes) {
data = data.replace('<svg', '<svg '+attributes);
}
return data;
});
/* all your other config stuff */
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment