Ryanthehouse Ryanthehouse - 2 months ago 9
PHP Question

Load page specific resource(s) using @include

How do I load page specific resource(s) using

@include
of the Laravel blade template engine?

Below is the content of my Master layout (
master.blade.php
):

<head>
@section('styles')
{{-- Some Master Styles --}}
@show
</head>
<body>
{{-- Header --}}
@section('header')
@include('header')
@show

{{-- Content --}}
@section('content')
{{-- Content for page is extending this view --}}
@show

{{-- Footer --}}
@section('footer')
@include('footer')
@show
</body>


In a given page, I make use of my master template this way:

@extends('master')

@section('styles')
@parent
{{-- Page Stylesheet --}}
@endsection


The approach above is what I use to try and load my page specific style to the
<head>
section.

It does not work properly as expected.

I would like to as well load other page specific resource(s) in my footer using the same approach; how can I do that effectively?

Answer

You don't need to do

@extends('master')

@section('styles')
    @parent
    {{-- Page Stylesheet --}}
@endsection

in your respective pages so as to load page specific stylesheets.

You should rather load page specific stylesheets for your master.blade.php file so as to keep your code dry.

To to that, you shout specify the route or expected url format of such pages, then, the appropriate stylesheet(s) to be loaded.

You can do that this way in your master.blade.php file:

@section('styles')
    @if(Request::is('transactions/generate-invoice'))
        @include('generate-invoice-css')
    @elseif(Request::is('transactions/users'))
        @include('users-css')
    @endif
@show

Where generate-invoice-css.blade.php contains the stylesheet(s) you want loaded for the page content accessible at yoursite.com/transactions/generate-invoice and users-css.blade.php, that of yoursite.com/transactions/users.

For a given pattern as in: same stylesheets for pages under transactions, you can do this:

@if(Request::is('transactions*'))

using a wildcard *.

To load a given resource to a location other than the <head> section of your pages, simply use the same approach and adapt as appropriate.

To load page specific resources with an @include() from your master.blade.php, use this approach (in your master.blade.php file):

@section('styles')
    @include('styles')
@show

where styles.blade.php should contain those your conditions for the appropriate resources to be loaded satisfying your requirement(s) for the purpose as in:

@if(Request::is('transactions/generate-invoice'))
    @include('generate-invoice-css')
@elseif(Request::is('transactions/users'))
    @include('users-css')
@endif

As the content of your styles.blade.php.

Comments