How to include javascript files on specific pages with Blade in Laravel

Categorized as Laravel Tagged

There is a beautiful trick to make this happen with Laravel.

First, you need to specify @stack method in your main blade file (the wrapper) or in the file for javascript includes. Second, you need to “push” from your specific page the needed javascript include.

For example, we have this blade files structure:

  1. /views/main.blade.php, the wrapper for our pages
  2. /views/partials/javascript.blade.php, javascript file includes
  3. /view/posts/single.blade.php, blog post file, which has to have its own javascript file included
// views/main.blade.php

<!DOCTYPE html>
<html>
<head>@include('partials.head')</head>
<body>

  @include('partials.nav')

  <main>
    @include('partials.messages')
    @yield('content')
  </main>

  @include('partials.footer')

  @include('partials.javascript')

</body>
</html>
// views/partials/javascript.blade.php

@stack('scripts')
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
// views/partials/single.blade.php

@extends('main')

@push('scripts')
<script defer src="https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js"></script>
@endpush

@section('content')

...

@endsection

Now, your post page specific javascript is being pushed where it is needed and exists only on the blog pages. Enjoy!

Leave a reply

Your email address will not be published.