Including SVG contents in Laravel 5 Blade template
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') !!}
View Composer Method
I ended up using a view composer in a service provider.
In the service provider's boot()
method:
// Wildcard view composer
view()->composer('*', function($view) {
// Instantiate new DOMDocument object
$svg = new DOMDocument();
// Load SVG file from public folder
$svg->load(public_path('images/logo.svg'));
// Add CSS class (you can omit this line)
$svg->documentElement->setAttribute("class", "logo");
// Get XML without version element
$logo = $svg->saveXML($svg->documentElement);
// Attach data to view
$view->with('logo', $logo);
});
And in my view:
<!-- Echo unescaped SVG content -->
{!! $logo !!}
I am using DOMDocument
as it allows me to remove the XML version element which should not be in the HTML.
The CSS class is not essential but saves me wrapping the logo with another HTML element for styling.
If you only need the logo in a specific Blade partial such as header you could write
view()->composer('header', function($view) {});
http://laravel.com/docs/5.0/views#view-composers
https://laracasts.com/series/laravel-5-fundamentals/episodes/25
Blade Partial Method
This method is not best practice since this sort of code should not really be in a view. However it is very simple and much better than adding PHP code in every single view.
Make a new partial (lets say logo.blade.php) with the following code:
<?php
// Instantiate new DOMDocument object
$svg = new DOMDocument();
// Load SVG file from public folder
$svg->load(public_path('images/logo.svg'));
// Add CSS class (you can omit this line)
$svg->documentElement->setAttribute("class", "logo");
// Echo XML without version element
echo $svg->saveXML($svg->documentElement);
?>
You can now use the SVG image in a blade template by including the partial like so:
@include('logo')
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')