Skip to content

Instantly share code, notes, and snippets.

@relliv
Last active May 29, 2021 22:23
Show Gist options
  • Save relliv/28cb441e415b31323f36f3d0aac3d95c to your computer and use it in GitHub Desktop.
Save relliv/28cb441e415b31323f36f3d0aac3d95c to your computer and use it in GitHub Desktop.
Laravel SVG loader directive example
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\File;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
// ...
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// ...
$this->setDirectives();
}
private function setDirectives(){
Blade::directive('svg', function($arguments) {
$arguments = array_map(function($item) {
return trim($item, ' \'');
}, array_pad(explode(',', $arguments), 2, ''));
$svgLocation = 'assets\node_modules\@fortawesome\fontawesome-free\svgs';
$icon = $arguments[0] ?? null;
$type = $arguments[1] ?? null;
$class = $arguments[2] ?? null;
if ($icon && $type){
$svgFilePath = public_path($svgLocation.'\\'.$type.'\\'.$icon.'.svg');
$svgFilePath = str_replace('\\', DIRECTORY_SEPARATOR, $svgFilePath);
if (File::exists($svgFilePath)){
$svg = new \DOMDocument();
$svg->load($svgFilePath);
$svg->documentElement->setAttribute("class", 'fa-svg '.$class);
$output = $svg->saveXML($svg->documentElement);
return $output;
}
return 'svg not found';
}
return 'invalid svg parameters';
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment