SVG sprites workflow

I made an @icons directive, although it’s…maybe not great:

// config/assets.php
'path' => get_theme_file_path().'/dist',

// app/helpers.php
function locate_asset($asset)
{
   return trailingslashit(config('assets.path')) . sage('assets')->get($asset);
}

// app/setup.php
sage('blade')->compiler()->directive('icon', function ($asset) {
    $asset = trim($asset, " '\"");
    $asset = str_replace("'", "\"", $asset);

    /**
    * There isn't a good way to break up this string, so we're
    * going to ignore standards for a bit.
    */
    // @codingStandardsIgnoreStart
    return '<?php $asset = "' . $asset . '"; $true_asset = ' . __NAMESPACE__ . '\\locate_asset($asset); ?><span class="a-icon a-icon--<?= basename($asset, \'.svg\') ?>"><?= file_get_contents($true_asset); ?></span>';
     // @codingStandardsIgnoreEnd
 });

Usage:

@icon('images/icon-search.svg')
// or if you want to process variables...
@icon('images/social/'.$network->slug.'.svg')

Also made a simple @inline directive that doesn’t try and do the wrapping stuff:

// app/setup.php
sage('blade')->compiler()->directive('inline', function ($asset) {
    $asset = trim($asset, " '\"");
    return "<?= file_get_contents(". __NAMESPACE__ . "\\locate_asset('" . $asset . "')); ?>";
 });
8 Likes