What is the best way to include the contents of an SVG file (located in the assets folder) in a Laravel 5 blade template?
I don't want to use image/object/embed tags, this should be an inline SVG for reasons of speed.
I know I could use <?php file_get_contents("file.svg") ?>
but is there a better way specific to Laravel/Blade?
Edit: to clarify, the method should work with all SVG files, including the one below.
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg">
<path stroke="red" fill="#00f" d="M10 10h100v100H10z"/>
</svg>
Similar to the accepted answer but a bit cleaner (imo).
Use the laravel directive to extend blade, like so (in your App Service Provider, as outlined here):
\Blade::directive('svg', function($arguments) {
// Funky madness to accept multiple arguments into the directive
list($path, $class) = array_pad(explode(',', trim($arguments, "() ")), 2, '');
$path = trim($path, "' ");
$class = trim($class, "' ");
// Create the dom document as per the other answers
$svg = new \DOMDocument();
$svg->load(public_path($path));
$svg->documentElement->setAttribute("class", $class);
$output = $svg->saveXML($svg->documentElement);
return $output;
});
Then use it in your blade like so:
<div class="Login__image Login__cloud">
@svg('cloud.svg', 'Cloud')
</div>
This works, that's the simplest way I could think about :
{!! file_get_contents('images/icon.svg') !!}
Why not place the svg into a blade template?
resources/views/icons/dashboard.blade.php
then add in your views using blade syntax?
@include('icons.dashboard')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With