Summer Sale! All accounts are 50% off this week.

mstdmstd's avatar

How to set path of svg file in blade directive?

Hello, In my Laravel 8 app I want to add svg files and reading this https://stackoverflow.com/questions/30058556/including-svg-contents-in-laravel-5-blade-template

I added svg support directive in app/Providers/AppServiceProvider.php :

    public function boot()
    {

        \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;
        });

and in blade file :

        <div class="Login__image Login__cloud">
            @svg($countryFlagUrl, 'Cloud')
        </div>

and I got error :

DOMDocument::load(): I/O warning : failed to load external entity &quot;/mnt/_work_sdb8/wwwroot/lar/AdsBackend8/public/$countryFlagUrl&quot;

If to comment line

            @svg($countryFlagUrl, 'Cloud')

line with $countryFlagUrl output valid path to svg file :

$countryFlagUrl::/images/flags/afg.svg

Looks like var $countryFlagUrl was not rendered inside of the directive. Which is the valid way ?

Thanks!

0 likes
4 replies
RahulKmOfficial's avatar

in laravel 8 you can manage your svgs in more simple way which i use most. make a mysvg.blade.php component & inside that component

@props ['name']

@if ($name === "svgname"  )
<svg>........</svg>
@elseif($name === "mysvg1"  )
<svg>........</svg>
@elseif
............

###insted of svg tag you can use img too but i like svg because of better control.

on your blade just use

<x-mysvg name="mysvg1" class="" />
mstdmstd's avatar

I asked about different : my variable with flag name is not rendered inside of @sdvg construction. This way does not work also :

        <div class="Login__image Login__cloud">
            @svg( {{ $countryFlagUrl }}, 'Cloud' )
        </div>

I got error :

DOMDocument::load(): I/O warning : failed to load external entity &quot;/mnt/_work_sdb8/wwwroot/lar/AdsBackend8/public/{{ $countryFlagUrl }}&quot;

Also I tried to use function from helper file :

        <div class="Login__image Login__cloud">
            @svg( getCountryFlagUrl(), 'Cloud' )
        </div>

and error again.

as listing of countries is rather big I can not make @if condition with all possible flags.

mstdmstd's avatar

Is Blade SVG package already installed in Laravel 8 ? I can not find similar coinfig file... Please, link to description...

Please or to participate in this conversation.