Add external javascript files with blade engine code in Laravel 5.x?

I have multiple Javascript files, and lots of them are prepared by the laravel template engine. For example ill use:

@if ($group_id !== 3)
    //do something here
@endif

Everthing is fine, when ill include this the javascript code directly into my filename.blade.php template.

But i would like to load all external with:

<script type="text/javascript">
    $.getScript("js/pages/filename.js");
</script>

And so its not processed by the blade engine. Ill found some solutions for L4, but i am not really happy with them. For example youll should name your javascript files like javascript.blade.php and include it in that way – but so my IDE thinks its an PHP file and formats it totally wrong. Other solution here is to write your (group in this example) before you include it, like:
<script type="text/javascript">
    var group = {!! $group_id !!}
    $.getScript("js/pages/filename.js");
</script>

I am still not really happy with that solution, i would like that all files should be processed as it was included directly in my blade-file.

Is there a solution to handle that?

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Lets say you have the following external JS script (including some blade engine code as well) :

first.js

First of all in order to use this script in any of the other blade file, rename the above file to the following:

first.blade.php (But remember to place the whole script code inside script tag!!)

Now include this file inside your other blade file in the following way:

@include(‘someViewFolder.first’) assuming you had put the first.blade.php inside ‘someViewFolder‘ folder.

I hope this helps, Cheers.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x