skip to Main Content

Currently I have a single layout file. But now I need to add some css and js files to many of the pages, yet not all.

I don’t want to manually go to each page and @push the files to the styles/scripts stacks.

One of the ways I could do it is passing condition to the layout file:

@extends('layouts.master', ['more_assets' => true])

and

 // layouts/master.blade.php
@if ($extraAssets)
    <link rel="stylesheet" ...>
    <script src="..."></script>
@endif

But is there a better way to do it? Maybe extending the master layout into a secondary layout and include the files there, then on the relevant pages, extend the secondary layout?

The problem with that is, I don’t think I can inherit sections from the grandparent layout:

// layouts/master.blade.php
<html>
<head>
    <meta ...>
    <meta ...>
    <meta ...>
    
    <title> some title </title>

    <link href=" ... " rel="stylesheet">
    <link href=" ... " rel="stylesheet">
    <link href=" ... " rel="stylesheet">
    <link href=" ... " rel="stylesheet">
</head>
<body>

    <main>
        @yield('content')
    </main>
   
    <script src=" ... "></script>
    <script src=" ... " ></script>
    <script src=" ... " ></script>
    <script src=" ... "></script>

    @stack('scripts')
</body>
</html>

the secondary layout:

   // layouts/secondary.blade.php
    @extends('master')
    
    @push('styles')
        // push styles here
    @endpush
    
    @push('scripts')
        // push scripts here
    @endpush

Then I don’t think it can work:

@extends('secondary')

@section('content')
    // some content
@endsection

2

Answers


  1. You can use it like this

    the secondary layout:

    @extends(‘master’)

    @push('styles')
        // push styles here
    @endpush
    @section('content')
    @yield('content')
    @ensection
    
    @push('scripts')
        // push scripts here
    @endpush
    
    Login or Signup to reply.
  2. you can use laravel blade directive @stack on your master blade

    //on master
    @stack('custom-scripts')
    
    //on extended master blade
    @push('custom-scripts)
    <scripts> </scripts>
    @endpush
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search