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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With