DEV Community

Alexis
Alexis

Posted on

11ty: Inject SVG code using Shortcodes

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');
Enter fullscreen mode Exit fullscreen mode

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');
   }
}
Enter fullscreen mode Exit fullscreen mode

Next, create the new shortcode using the addShortcode function, like so:

config.addShortcode("svg", getSvgContent);
Enter fullscreen mode Exit fullscreen mode

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" %}
Enter fullscreen mode Exit fullscreen mode

If you want to use subfolders:

{% svg "subfolder/myfile" %}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Thanks for reading

Feel free to change it however you need. Don't forget to like, share, and comment ✌️

Top comments (1)

Collapse
 
hunvreus profile image
Ronan Berder

Alternatively:

  1. Drop your svg files in the _includes folder (e.g. _includes/icons/my-icon.svg),
  2. Use a regular include: {% include "icons/my-icon.svg" %}