Create a {% svg %}
shortcode to inject SVG icons, images, or illustration directly into your template.
Open the .eleventy.js
config file and add the following code at the top of the page:
const fs = require('fs');
Inside the Eleventy config create a new function that will get the SVG contents:
function eleventyConfig(config) {
let getSvgContent = function (file) {
let relativeFilePath = `./src/svg/${file}.svg`;
let data = fs.readFileSync(relativeFilePath,
function(err, contents) {
if (err) return err
return contents
});
return data.toString('utf8');
}
}
Next, create the new shortcode using the addShortcode
function, like so:
config.addShortcode("svg", getSvgContent);
Create a new folder in the src
folder, name it: svg
, and add a new vector file with the .svg
extension.
To use it in your templates, simply add the new shortcode tag and the file path:
{% svg "myfile" %}
If you want to use subfolders:
{% svg "subfolder/myfile" %}
Notice, we are only using the subfolder and file name, without any extension. That is because in our function we are doing this automatically.
That's it!
The full code
const fs = require('fs');
function eleventyConfig(config) {
let getSvgContent = function (file) {
let relativeFilePath = `./src/svg/${file}.svg`;
let data = fs.readFileSync(relativeFilePath,
function(err, contents) {
if (err) return err
return contents
});
return data.toString('utf8');
}
config.addShortcode("svg", getSvgContent);
}
module.exports = eleventyConfig;
Thanks for reading
Feel free to change it however you need. Don't forget to like, share, and comment โ๏ธ
Top comments (1)
Alternatively:
_includes
folder (e.g._includes/icons/my-icon.svg
),{% include "icons/my-icon.svg" %}