DEV Community

Alexandr
Alexandr

Posted on

Use inline SVG icons with Laravel

I used icons in fonts for a long time, just by connecting a file with styles and insert a tag with class names.

<i class="icon icon-home">
Enter fullscreen mode Exit fullscreen mode

It was quite simple. But over time, the began to use SVG format instead of fonts. Now, for the same post, it was not required to include styles, but the tag itself became much larger:

<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-house" viewBox="0 0 16 16">
  <path fill-rule="evenodd" d="M2 13.5V7h1v6.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V7h1v6.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5zm11-11V6l-2-2V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5z"/>
  <path fill-rule="evenodd" d="M7.293 1.5a1 1 0 0 1 1.414 0l6.647 6.646a.5.5 0 0 1-.708.708L8 2.207 1.354 8.854a.5.5 0 1 1-.708-.708L7.293 1.5z"/>
</svg>
Enter fullscreen mode Exit fullscreen mode

If the past could be remembered or rely on the IDE's auto-hints, then the inline tag is more difficult. I started looking for options on how to keep this in mind without complicating it. So I decided to write my own simple package that could display any icons by file name.

namespace App\Providers;

use Orchid\Icons\IconFinder;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(IconFinder $iconFinder) : void
    {
        $iconFinder->registerIconDirectory('fa', storage_path('app/fontawesome'));
    }
}
Enter fullscreen mode Exit fullscreen mode

When calling the directory method with the first argument, we pass the prefix to call our icons and the second directory where they are located.

After that, we can call the component in our blade templates:

<x-orchid-icon path="fa.home" />
Enter fullscreen mode Exit fullscreen mode

If you use one or two sets of icons that do not repeat, then it is not necessary to specify a prefix in the component:

<x-orchid-icon path="home" />
Enter fullscreen mode Exit fullscreen mode

You can also list some attributes that should be applied to your icon:

<x-orchid-icon 
    path="home" 
    class="icon-big" 
    width="2em" 
    height="2em" />
Enter fullscreen mode Exit fullscreen mode

As you can see, this is as simple as the past use of the tag with class names. And it is not tied to any set of icons. We independently from our set.

You can find this package on GitHub, in the place with the description: https://github.com/orchidsoftware/blade-icons

Top comments (0)