1

I'm wondering what could be a good way to dynamically include a js file in my main blade template like this

<?php
$currentRoute = Route::currentRouteName();
$currentRoute = $currentRoute?$currentRoute:'home';
$currentRoute = explode('.',$currentRoute);
  ?>
<script src="{{$currentRoute[0]}}.js"></script> 

but just a less tricky :)

1 Answer 1

5

I did something like that in that past. Here, is my "trick" to do this.

First you need a top level controller class

class MainController extends Controller {

   protected static $js_files  = [];
   protected static $css_files = [];

   public static function boot()
   {
      view()->share('js_files', static::$js_files);
      view()->share('css_files', static::$css_files);
      parent::boot();
   }
}

Then, all of your controllers must inherit from your MainController class.

The reason I use the keyword "static::" instead of "self::" is because I want to retrieve the latest child properties and not the "MainController" property, which would gave me the keywords "self::".

See http://php.net/manual/en/language.oop5.late-static-bindings.php In your blade layout, in the head section do the following :

@foreach($css_files as $src)
   <link href="{{$src}}" rel="stylesheet">
@endforeach

and before your closing body tag

@foreach($js_files as $src)
    <script src="{{$src}}"></script>
@endforeach

In each controllers, you have to put in the $js_files and $css_files inherited properties the sources of all of your js/css.

if you want to include a JS/CSS only for one route, you can add the source of the file directly in the method.

And voilà !

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

2 Comments

after extending MainController where to bind js and css in controller? Suppose i have create method then into that mehod? Also how to pass this variable into blade template?
You can do it wherever you want to. Constructor or any method you want.

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.