Extend custom base.php to child pages

EDITED: Originally I wrote a long post here about how to do this with Blade @stacks, not realizing that the original poster was looking for help with Sage 8. I’ve modified this post to be a better example, and left it here in case it helps someone in the future.

A different approach to the whole problem might be a custom template, some basic logic, and a couple of blade @stacks.

Here’s an example of how @stacks work.

How to do this with Blade @stacks and Sage 9

functions.php

/**
 * Determine if the stack has content.
 *
 * Credit to KimH for this function
 * @param  string $stack
 * @return boolean
 */
function stack_has_content(string $stack) : bool
{
    return (boolean) trim(sage('blade')->yieldPushContent($stack));
}

layouts/app.blade.php

<!doctype html>
<html @php(language_attributes())>
  @include('partials.head')
  <body @php(body_class())>
    @php(do_action('get_header'))
    
    @if(stack_has_content('header'))

      @stack('header') <!-- add a header stack here -->
    
    @else

      @include('partials.header')

    @endif

    <div class="wrap container" role="document">
      <div class="content">
        <main class="main">
          @yield('content')
        </main>
        @if (App\display_sidebar())
          <aside class="sidebar">
            
            @if(stack_has_content('sidebar'))

              @stack('sidebar') <!-- add a header stack here -->
    
            @else

              @include('partials.sidebar')

            @endif

          </aside>
        @endif
      </div>
    </div>
    @php(do_action('get_footer'))
    @include('partials.footer')
    @php(wp_footer())
  </body>
</html>

views/template-custom.blade.php


{{--
  Template Name: Custom Template
--}}

<!-- populate the header stack with this include -->
@include('partials.header-custom') 

<!-- populate the sidebar stack with this include -->
@include('partials.sidebar-custom')

<!-- continue about our normal custom template -->
@extends('layouts.app')

@section('content')
  @while(have_posts()) @php(the_post())
    @include('partials.page-header')
    @include('partials.content-page')
  @endwhile
@endsection

views/partials/header-custom.blade.php

@push('header')

<!-- all your custom header html here -->  

@endpush

views/partials/sidebar-custom.blade.php

@push('sidebar')

<!-- all your custom sidebar html here -->  

@endpush

I cannot stress enough that this is untested, but it’s the general idea.

Stacks are super helpful for situations like this because they let you keep all your custom template stuff in one place (the custom template blade file), rather than messing around with a lot of logic, or a separate layout.

I hope this helps someone, some time.

2 Likes