How to include extra CSS and JS files for particular Blade Templates in Laravel 9? ,2024

I am using Laravel 9.0 and I want to include extra CSS and js files for a particular Blade Template file then we can use the following code to include a particular Blade file.

I’m working on setting up the blade hierarchy for my upcoming project and need some help setting up the extra script and js file for particular Blade Template file only:

Requirements:

  1. The sidebar will be available on most of the pages, but not all.
  2. Some of the Blade Templates will need custom JS injections and CSS as well.

Solution

  • We can use section() and yield() function
  • WE Can you push() and stack() function

I have provided both examples in my code stylesheet file including using section() and yield() method, and script file included using push() & stack method.

My main layout for the site: mainLayout.blade.php

<html>
    <head>
        <title><title>@yield('title') - Piyushmaurya.in</title></title>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
        @yield('stylesheets') <!-- Child will insert custom childsheets as required -->
    </head>
    <body>
        <div id="container">
            @yield('sidebar')
            @yield('content')
        </div>
        @stack('scripts')
    </body>
</html>

Example Child template: userList.blade.php

@extends('layouts.mainLayout')

@section('title', 'page Title')
@section('stylesheets')
    <link rel="stylesheet" href="custom/css/required/by/child">
@endsection

@section('sidebar')
    <div class="sidebar">
        <div>Some sidebar stuff</>
    </div>
@endsection

@section('content')
    
@endsection

@push('scripts')
    <script src="{{ URL::asset('custom/js/required/myscript.js') }}"></script>
@endpush

Discover more from STRUGGLER KING.COM

Subscribe now to keep reading and get access to the full archive.

Continue Reading