Using Laravel functions inside a javascript file that is included as an asset

Let's say I have a jQuery javascript piece that binds to a div at loading and dynamically defines img in that div. Something like that:

$(document).ready(function() { $("#container").html("<img href='/images/myimage.jpg/>'); }); 

If I used this built-in Laravel view, I could use HTML :: image () and Blade templates to indicate the location of the image. Something like that:

 $(document).ready(function() { $("#container").html("{{ HTML::image('images/myimage.jpg', 'My image') }}"); }); 

If I then took this piece of javascript and instead of pasting it into a view, put it in a separate .js file, say, public / js / image.js , I could use Laravel as an asset;

 Asset::add('image.js', 'js/image.js'); 

However, since now it is considered only as an asset, neither Laravel PHP nor the Blade template code is processed, so we literally get the line {{HTML :: image ('images / myimage.jpg', 'My image')}} in the received html instead of templated-in values.

Is there a good approach to something like this?

+4
source share
2 answers

I do it here. I found:

1 - create a "js" file inside the view directory tree, something like

 app\views\javascript\mycustomJS.blade.php 

2 - then visualize it where you need it:

 <script> @include('javascript.mycustomJS') </script> 

This blade, it will be processed as it should be.

This is far from ideal, I know, but now it works for me. :)

+4
source

I think you can put it in a php file. I have done this before using css.

 Asset::add('image.php', 'js/image.php'); 
0
source

Source: https://habr.com/ru/post/1481647/


All Articles