0

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 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's actually very neat, now I wonder if that's a good idea to use it or the other one I suggested at the post. In terms of maintenance, better practices etc..
Update: I just checked again, and it even inherits from the master without needing to yield another content in the child layout
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.