Laravel: How to display SVG images in Blade templates

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Scalable Vector Graphics, commonly known as SVG, is an XML-based image format for two-dimensional graphics which can be scaled indefinitely without loss of quality, making them a perfect candidate for responsive web design. In this tutorial, we’ll explore how to efficiently use SVG images within Blade templates, the templating engine of Laravel, a popular PHP web framework.

Why SVGs?

In web development, SVGs serve diverse roles, from logos to intricate illustrations, owing to their scaling flexibility and usually smaller file sizes compared to raster images such as JPEGs or PNGs. Additionally, since they’re XML-based, SVGs can be manipulated through CSS or JavaScript, thus allowing for interactive and dynamic graphic content.

Basic SVG Usage in Blade

To begin using SVG images in y

<!-- resources/views/your_view.blade.php -->
<div>
    {!! file_get_contents(public_path('images/logo.svg')) !!}
</div>

You can use the file_get_contents PHP function to read the SVG file content and then, use the {!! !!} notation to output it unescaped in your Blade template.

SVG Blade Component

For frequent use, it would be great to encapsulate the SVG loading logic within a re-usable Blade component.

<!-- resources/views/components/svg.blade.php -->
@php
    $svg = file_get_contents(public_path($name . '.svg'));
@endphp
{!! $svg !!}

And in Blade, you would use this component like so:

<x-svg name="logo" />

The component reads in the specified SVG file by name and embeds it into the HTML.

Controlling SVG Styles

An embedded SVG can be styled similarly to an HTML element using CSS.

<style>
    .svg-logo {
        height: 50px;
        width: auto;
        fill: #3490dc;
    }
</style>

<!-- In Blade -->
<div class="svg-logo">
    {!! file_get_contents(public_path('images/logo.svg')) !!}
</div>

This method will allow overarching style control over the SVG element.

Caching SVG Output

Serving up raw file contents on each request can lead to a performance hit. A better approach is to cache the SVG output. You can wrap the file_get_contents call within Laravel’s caching facade to do so:

<!-- resources/views/your_view.blade.php -->
{!! Cache::remember('svg.logo', 60*24, function() {
    return file_get_contents(public_path('images/logo.svg'));
}) !!}

This will store the output of the file in the cache and serve it from there on subsequent requests.

Packages for SVG Rendering in Laravel

If you want more advanced features like inline SVG rendering and manipulation, you might consider a package like Blade Icons:

composer require blade-ui-kit/blade-icons

After installing, you can add your custom SVGs to a dedicated folder and reference them using the package directives:

<x-icon name="logo" />

This provides a clean and simple syntax for SVGs.

Advanced SVG Manipulation

In more complex scenarios, where let’s say, you need to modify parts of the SVG dynamically, you can leverage Laravel’s view composers in conjunction with Blade components.

<!-- resources/views/components/dynamic-svg.blade.php -->
@php
    $svgContents = file_get_contents(public_path($name . '.svg'));
    $svgContents = preg_replace('/#originalColor/', $color, $svgContents);
@endphp
{!! $svgContents !!}

Using preg_replace, we can dynamically change certain aspects of the SVG before rendering, this could be fill color, sizing or any attribute within the SVG XML.

Securing SVG Content

When loading SVGs or any kind of user-supplied content, security should be the top priority. Always ensure SVGs are sanitized to prevent potential XSS attacks. For sanitization, you could use a package like DOMPurify on the client-side or opt for a PHP solution:

composer require enshrined/svg-sanitize

And then sanitize before output:

$safeSVG = SVG::sanitize($dirtySVG); 
{!! $safeSVG !!}

Conclusion

Using SVG images in Blade templates can enhance your application’s scalability and responsiveness. Whether you’re embedding directly, through a component, adding advanced manipulations, or companion packages – the key is to use them thoughtfully for optimal performance and security. Keep scalability and safety in mind, and your graphics will shine on all devices.