Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including SVG contents in Laravel 5 Blade template

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>
like image 667
Michael Lawton Avatar asked May 05 '15 16:05

Michael Lawton


3 Answers

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>
like image 166
Chris Avatar answered Nov 14 '22 15:11

Chris


This works, that's the simplest way I could think about :

{!! file_get_contents('images/icon.svg') !!}
like image 27
Romain Avatar answered Nov 14 '22 16:11

Romain


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')
like image 20
zeros-and-ones Avatar answered Nov 14 '22 14:11

zeros-and-ones