Is there a way to use @push and @stack for complex laravel blade layout?

Viewed 569

Working with blade I have a layout and I have created a package that has several view blade components, this components are then render on the apps blade as follows.

layout > apps

 <head>
    @stack('css')
    @yield('styles')
    </head>
     <body>
     <main class="py-4">
        @yield('content')
        {{--Render package components--}}
        @includeIf('package::view-blade')
      </main>
         @yield('scripts')
      </body>

I am able to render scripts from the components as follows:

package > resources > components > view-blade

@section('scripts')
    @parent
    <script src="{{asset('path-to-scripts')}}"></script>
@endsection

But when I try the same for styles it does not work, i.e

@section('styles')
        @parent
        <link type="text/css" href="{{asset('path-to-styles')}}"/>
    @endsection

Or

@push('css')
<link type="text/css" href="{{asset('path-to-styles')}}"/>
@endpush

How can i render styles to the app.blade file dynamically from the package component file?

2 Answers

I realized that for @push to work the file has to use @extends. since I was rendering the component directly into the layout app.blade, this means it could not work. Essentially I was setting the file as

 <head>
    @stack('css')
    @yield('styles')
    </head>
     <body>
     <main class="py-4">
        @yield('content')
        {{--Render package components--}}
      @section('styles')
        @parent
        <link type="text/css" href="{{asset('path-to-styles')}}"/>
    @endsection
      </main>
         @yield('scripts')
      </body>

What I don't get is why the scripts worked but not the styles.

Any way I was able to sort it by moving the code @includeIf('package::view-blade') to a separate welcome.blade file which extends the app layout.

Instead of @yield use @stack

<head>
    @stack('css')
    @stack('styles')
    </head>
     <body>
     <main class="py-4">
        @yield('content')
        {{--Render package components--}}
        @includeIf('package::view-blade')
      </main>
         @stack('scripts')
      </body>

package > resources > components > view-blade

@push('styles')
    <link type="text/css" href="{{asset('path-to-styles')}}"/>
@push
Related