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?
Laravel Blade: What is best practice for adding javascript in blade files?
Asked Answered
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.
if you use webpack.mix.js
:
mix.js('resources/js/app.js', 'public/js')
.js('resources/js/my-super-amazing-script.js', 'public/js')
And in your main my-layout.blade.php
:
...
@yield('javascript')
</body>
Then, in your specific page :
@extend('my-layout.blade.php')
...
@once
@push('javascript')
<script src="{{ mix('js/my-super-amazing-script.js') }}" defer></script>
@endpush
@endonce
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
© 2022 - 2024 — McMap. All rights reserved.