2

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

6
  • 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. Commented Oct 17, 2017 at 15:57
  • You entirely can - in fact I've used this more times than I care to admit in Laravel. Commented Oct 17, 2017 at 15:57
  • @Tor did you do it the same way i did? Commented Oct 17, 2017 at 15:58
  • @Yosef 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. Commented Oct 17, 2017 at 15:59
  • putting an image in a javascript variable is a bit unclear. Do you mean a url? or what. Commented Oct 17, 2017 at 15:59

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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') }}'

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.