In Laravel, you can conditionally include or exclude JavaScript and CSS files based on the current page by using the built-in @section
directive and the @yield
directive in the Blade templates.
Here's an example of how you can achieve this:
Step 1: Open your main layout file (usually located in resources/views/layouts/app.blade.php
) and define the sections where you want to include or exclude the JavaScript and CSS files. For example:
<!-- app.blade.php -->
<html>
<head>
<!-- Include global CSS files -->
<link href="{{ asset('css/global.css') }}" rel="stylesheet">
<!-- Yield a section for page-specific CSS files -->
@yield('css')
</head>
<body>
<!-- Include global JavaScript files -->
<script src="{{ asset('js/global.js') }}"></script>
<!-- Yield a section for page-specific JavaScript files -->
@yield('scripts')
</body>
</html>
Step 2: In your page-specific Blade templates, extend the main layout file and define the section content. For example, in resources/views/home.blade.php
:
<!-- home.blade.php -->
@extends('layouts.app')
@section('css')
<!-- Include home-specific CSS file -->
<link href="{{ asset('css/home.css') }}" rel="stylesheet">
@endsection
@section('scripts')
<!-- Include home-specific JavaScript file -->
<script src="{{ asset('js/home.js') }}"></script>
@endsection
<!-- Rest of the page content -->
Step 3: In other page-specific Blade templates, you can conditionally include or exclude the JavaScript and CSS files by defining different contents for the @section
directives. For example, in resources/views/about.blade.php
:
<!-- about.blade.php -->
@extends('layouts.app')
@section('css')
<!-- Include about-specific CSS file -->
<link href="{{ asset('css/about.css') }}" rel="stylesheet">
@endsection
<!-- No JavaScript files needed for this page -->
<!-- Rest of the page content -->
This way, the @yield
directives in the main layout file will dynamically include the appropriate CSS and JavaScript files based on the current page being rendered.