Inline SVGs are a lesser known trick for performant assets. Using them in traditional static sites is problematic due to how verbose they are. Inline SVGs can be anywhere from a few lines of code to a hundred! Not the prettiest solution. That is why it’s much better to use a component based approach. Using something like Vue.js, it’s pretty trivial to make SVG’s their own component.
In this article, I cover how to do this with Laravel Blade & the Sage 9 WordPress starter theme.
Benefits of Inline SVGs
Inline SVGs allow you to edit the shape and color directly using CSS. Why is this beneficial?
Using Assets With Different Colors: Something like a check mark is simple enough to include as an inline SVG. Let’s say you want a purple checkmark on one page, and green on the other. Why have two completely different assets when you can use a single SVG? Changing an inline SVG’s color is as simple as a CSS
Animating Images & Icons: Never could you animate the color of an image on hover. With SVG’s, doing this is actually pretty easy! Animating an inline SVG is similar to editing a webfont such as Font Awesome.
The benefits are only limited by your imagination. There are plenty of useful and creative uses of inline SVGs on the web.
How to Implement Inline SVGs with The Blade Templates
You could just use regular components, but that has the potential to get unorganized. You can use a blade directive such as
@svg so you can specify it from any template like so:
@svg('checkmark'). This article will not go into how to do that yourself. Instead, we will be using an easy to install library.
You can install blade-svg with composer using
. According to the docs, you should put your SVG icons in the
composer require nothingworks/blade-svg
From any template, you should now be able to use the blade directive
@svg. To render an icon, just use it with the name of the file in your icons folder. For
checkmark.png, you’d use
@svg('checkmark') in your template.
The second argument of this directive will add a class to the rendered icon. For example:
@svg('icon','icon-class') will add
icon-class to the rendered SVG.
As far as basics go, that’s pretty much it! If you want to learn more, just visit the Github page for this library. It contains more usage examples and information on how to use spritesheets.