Laravel, right way to import javascript into Blade Templates
Solution 1:
Anything outside of your @section
block will not be rendered.
You could edit your layouts/app.blade.php
and add a @stack('head')
where you want your styles/javascript to appear (preferably in the <head>
section of your HTML).
In any blade file that @extends('layouts.app')
you can then use
@push('head')
<!-- Styles -->
<link href="{{ asset('css/pizza.css') }}" rel="stylesheet">
<!-- Scripts -->
<script src="{{ asset('js/components/pizza.js')}}"></script>
@endpush
to push content into that stack.
For more information visit https://laravel.com/docs/5.6/blade#stacks
Solution 2:
For custom scripts on specific page,
-
add
@yield('footer-scripts'
) tolayouts/app.blade.php
-
create a folder named
'scripts'
in views folder -
inside
views/scripts
folder create a file 'pizza-script.blade.php
' and add the js file contents inside<script src="/path/to/pizza.js" /> <!-- it might not work if path isn't clear --> <script type="text/javascript"> console.log('executing js here..') js file contents.... #if jquery needed add it like, $(document).ready(function(){ ... } </script>
-
in your index.blade.php (or the page where you want the scripts to execute) at the end add the script after
@endsection
@section('footer-scripts') @include('scripts.pizza-script') @endsection
now refresh the page, you can see 'executing js here..'
on the console.