Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Blade: What is best practice for adding javascript in blade files?

I inherited a Laravel project that has many blade files with javascript inside tags within the blade file. The issue is that there is a lot of repetitive JS logic so I'd like to extract the JS and create JS files to include in the blade? Example: <script src="{{ asset('js/components/file.js')}}"></script> Is this the best practice for blade files or is it expected to be have the JS within the actual file?

like image 848
cmcmnooe Avatar asked Dec 13 '22 12:12

cmcmnooe


2 Answers

First you have to assign where yo want to push scripts in your layout. for example, say layout.blade.php is your main layout file and you want to inject codes after footer. So add

@stack('scripts')

after footer.

Now in your blade file, use @push to inject your code.

@push('scripts')
<script>
// your code
</script>
@endpush

check blade stack for further detail.

like image 71
Abdullah Al Shakib Avatar answered Dec 16 '22 00:12

Abdullah Al Shakib


I recommend you to maintain a specific section for page-specific javascript.

Please refer the following examples..

Example template.blade.php

  <body>

    @yield('content')

    @include('_partial.scripts')

    @yield('page-script')

    @include('_partial.footer')

</body>

then

@section('page-script')
<script type="text/javascript">
    // your custom script
</script>
@stop
like image 32
Lakitha Dias Avatar answered Dec 16 '22 01:12

Lakitha Dias