Skip to content

How to Dynamically Include SVGs Inline with Jekyll

David Ensinger

For (my website about local folks who make websites), I link to the social media accounts of the people I profile to help promote the work they do. To do this, I dynamically include an SVG icon (and link) for each of their respective social media accounts. The SVG icons are kept in the _includes/social-icons/ directory and they’re added to the page template with some YAML Front Matter and a Liquid for loop.

YAML Front Matter

Each social media account gets a title, url, and a class, which are then used by the Liquid for loop to generate the markup.

 - title: GitHub
   class: github
 - title: LinkedIn
   class: linkedin
 - title: Twitter
   class: twitter

Liquid For Loop

We loop through each social media account in the YAML Front Matter. An include prints out the SVG icon markup inline, which essentially results in {% include social-icons/github.svg %} for each SVG icon. The respective URL and title are pulled from the loop as well.

{% for icon in social-icons %}
  <a class="social-icon--link {{ icon.class }}" href="{{ icon.url }}">
    {% include {{ icon.class | prepend: 'social-icons/' | append: '.svg' }} %}
    <span class="social-icon--title visuallyHidden">{{ icon.title }}</span>
{% endfor %}

Resulting HTML

Here’s what the resulting HTML output looks like:

<a class="social-icon--link github" href="">
  <svg class="social-icon--svg github"></svg>
  <span class="social-icon--title visuallyHidden">GitHub</span>
<a class="social-icon--link linkedin" href="">
  <svg class="social-icon--svg linkedin"></svg>
  <span class="social-icon--title visuallyHidden">LinkedIn</span>
<a class="social-icon--link twitter" href="">
  <svg class="social-icon--svg twitter"></svg>
  <span class="social-icon--title visuallyHidden">Twitter</span>


It’s an elegant way to dynamically include the social media icons and links. Thankfully it wasn’t difficult to set up and it has proven easy to maintain. I did spend a lot of time making the dozens of social media icons, but that was all upfront work.