Yosef
Yosef

Reputation: 442

Use blade inside a JavaScript variable

I woke up this morning with a stupid question. Can you put blade inside a JavaScript variable:

 var NoImg = '{{ asset('img/ni-img.png') }}';

that will output as a string, all I need is it to output an image

Upvotes: 2

Views: 7589

Answers (3)

ceejayoz
ceejayoz

Reputation: 179994

Yes, but it's best to use json_encode to make sure the resulting output is JavaScript-friendly:

var NoImg = {!! json_encode(asset('img/ni-img.png')) !!};

PHP will add the quotation marks (for strings), any necessary escaping characters (if you have a ' in your filename, for example), and will handle more complex data structures like arrays/objects too.

Upvotes: 3

Mauricio Rodrigues
Mauricio Rodrigues

Reputation: 807

Yes. Blade is a server side template engine. If your have a blade view file, her will be executed before the javascript. In your case, NoImg will have the expanded value returned by the helper asset() when the html is returned from the server.

This will be work fine:

<?php
    // variable from your controller...
    $image = 'https://images.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
?>

// your js inside of a blade file...
var image = new Image(272, 92);
image.src = '{{ $image }}'; // or asset("path/to/your/image.png")
document.body.appendChild(image);

Upvotes: 0

Tor
Tor

Reputation: 784

Yep - that will directly inject the path to your image into your JS string's single-quotes.

If you needed to then use that string as an image, you'd need to set an img .src to the path, like

document.getElementByID('myImage').src = '{{ asset('img/ni-img.png') }}'

Upvotes: 1

Related Questions