最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

laravel - Use blade inside a JavaScript variable - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Oct 17, 2017 at 15:55 YosefYosef 4421 gold badge7 silver badges26 bronze badges 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. – Mauricio Rodrigues 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. – Tor Commented Oct 17, 2017 at 15:57
  • @Tor did you do it the same way i did? – Yosef 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. – Tor 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. – Kevin B Commented Oct 17, 2017 at 15:59
 |  Show 1 more ment

3 Answers 3

Reset to default 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 plex data structures like arrays/objects too.

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

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./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);
发布评论

评论列表(0)

  1. 暂无评论