Last active
June 26, 2022 14:44
-
-
Save patrickhlauke/99bb379963225aedde12d35dc70509b0 to your computer and use it in GitHub Desktop.
Fragment for `.eleventy.js` for a slightly modified svg shortcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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