Last active
May 29, 2021 22:23
-
-
Save relliv/28cb441e415b31323f36f3d0aac3d95c to your computer and use it in GitHub Desktop.
Laravel SVG loader directive example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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