Click to share! ⬇️

Laravel Blade Master Template Configuration

The Blade Master Template is going to be your best friend. In the last episode we started to work with rendering views in Laravel. Recall, this amounts to doing something like return view('file'), where file is the name of the view we want to render. In this episode we’ll take a look at the concept of using a master template to act as the blueprint for our views. It is a fantastic way to reuse code, and almost works in a similar way to the idea of having a class you can extend. The master template is the class, and the individual view files extend the master to allow for easy code reuse. Let’s take a look at how to do this now.


Create The Master Page

The Blade Master Template is where we can place all the boilerplate that all pages will typically make use of. Most times you can name this file something like master.blade.php. All view files that you would like to have make use of your master page can now use the @extends keyword to do so. Since our master page has the name of master.blade.php, in our view files we will use @extends('master'). You can name the master page something else if you want to, you’ll just need to make sure to extend the other name. For example if your master page is default.blade.php, you can use @extends(‘default‘) in your view files.

Laravel Blade Master Template
God Bless Auto Complete

Here is the master page we created for this demonstration.

\resources\views\master.blade.php source


<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>

<body>
<div class="container">
    @yield('content')
</div>

</body>
</html>

Excellent. Let’s note a few things here. Thanks to PHP Storm, we are able to quickly format the source so that everything gets indented nicely and so on. The ctrl + alt + L key combination are what we need for this. Next, since there is no possible way I can remember all the classes available in bootstrap, (or method calls in Laravel for that matter), PHP Storm saves the day with simply superb auto complete functionality. Being able to start typing, and then seeing all of your available options is really fantastic. Working with the Blade Master Template really becomes a joy in this way.


Master Pages yield Content

Within the master page, we need a way to display the sub views so to speak. Think of this like a placeholder, or almost like an include() statement in native PHP. What the @yield keyword does, is to import a named section of content. Let’s see our updated view file which we have modified to extend our master template file.

\resources\views\helloworld.blade.php source


@extends('master')

@section('content')

    <div class="jumbotron">
        <h1>{{ $variableone  }}</h1>

        <p>{{  $variabletwo  }}</p>

        <p><a class="btn btn-primary btn-lg" href="#" role="button"> {{  $variablethree  }}</a></p>
    </div>

@endsection

laravel master page screenshot

This is a good example of how named sections work. In our master page we yield a section called content. In our view file that extends the master page then, we need a way to name the content we are referring to. We do this with the @section and @endsection keywords. Note that the @section keyword must also have an associated name. In this case it is @section('content'). Basically, anything that comes between these two keywords, is the content that gets injected at @yield('content') in the master page. We can say then that @section / @endsection define the content, and @yield makes use of it.


Include Navigation And Footer With Master Template

We can also include subviews into the master layout. Maybe we would like to include a navigation area, in addition to a footer. Let’s see how to do that. First we’ll show the updated master template, then all of the associated sub views.


\resources\views\master.blade.php source


<html>
<head>
    <!-- Latest compiled and minified jquery -->
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>

<body>

<div class="container">
    @include('navigation')

    @yield('content')

    @include('footer')
</div>

</body>
</html>

\resources\views\navigation.blade.php source


<nav class="navbar navbar-default">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">{{ $brand }}</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown
                        <span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li><a href="#">Action</a></li>
                        <li><a href="#">Another action</a></li>
                        <li><a href="#">Something else here</a></li>
                        <li class="divider"></li>
                        <li><a href="#">Separated link</a></li>
                        <li class="divider"></li>
                        <li><a href="#">One more separated link</a></li>
                    </ul>
                </li>
            </ul>
            <form class="navbar-form navbar-left" role="search">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="{{ $navsearch }}">
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>

        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
</nav>

\resources\views\helloworld.blade.php source


@extends('master')

@section('content')

    <div class="jumbotron">
        <h1>{{ $variableone  }}</h1>

        <p>{{  $variabletwo  }}</p>

        <p><a class="btn btn-primary btn-lg" href="#" role="button"> {{  $variablethree  }}</a></p>
    </div>

@endsection

\resources\views\footer.blade.php source


<div class="panel panel-default">
    <div class="panel-body">
        Wicked Awesome Website.
    </div>
    <div class="panel-footer">{{ $footer }}</div>
</div>

Note! Even though we are including sub views into the master layout, when we render the helloworld view from our controller, any data passed to that view are also available to the sub views of the master template. We will populate the controller with some variables to make use of in the navigation area as well as the footer area.


\App\Http\Controllers\HelloWorldController.php source


<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class HelloWorldController extends Controller
{

    public function index()
    {
        $data['brand'] = 'Wicked Awesome Website';
        $data['navsearch'] = 'Search Now!';

        $data['variableone'] = 'The value of variable one.';
        $data['variabletwo'] = 'The value of variable two.';
        $data['variablethree'] = 'The value of variable three.';

        $data['footer'] = 'Trademark, Copyright, and all that Jazz';

        return view('helloworld')->with($data);
    }

}

Note that we added a brand, navsearch, and footer key to the $data array. When we pass this to the view being rendered, we will now have the variables of $brand, $navsearch, and $footer to work with in the navigation and footer areas. Let’s try it out.

laravel master template


Looping Through Data With Blade

The final topic we’ll cover in this tutorial is looping over data with blade. Most times, we’ll have some type of collection of data that the controller received from a model or in some other way. When we have this collection, we want to be able to loop over it. Maybe you have a website about video games, and you need to output a list of the names of various games. Let’s see how to do this.


\App\Http\Controllers\HelloWorldController.php source


<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class HelloWorldController extends Controller
{

    public function index()
    {
        $data['brand'] = 'Wicked Awesome Website';
        $data['navsearch'] = 'Search Now!';

        $data['variableone'] = 'Video Games';
        $data['variabletwo'] = 'Great games for all gamers.';

        $data['games'] = ['Super Mario 3D World', 'Mario Kart 8', 'Batman Legends', 'The Lego Movie'];

        $data['footer'] = 'Trademark, Copyright, and all that Jazz';

        return view('helloworld')->with($data);
    }

}

@foreach and @endforeach

Now we can add the updated code to the view in order to loop through our results.


@extends('master')

@section('content')

    <div class="jumbotron">
        <h1>{{ $variableone  }}</h1>

        <p>{{  $variabletwo  }}</p>

        @foreach($games as $game)
            <p class="text-primary">{{ $game }}</p>
        @endforeach
    </div>

@endsection

Laravel foreach endforeach

Laravel Blade Master Template Configuration Conclusion

In this episode we took just a quick look at setting up a master template with the Laravel blade template engine. There is a bit of a learning curve, however it is really elegant, and quick to use once you get used to it. Add in a fantastic IDE like PHP Storm that supports autocomplete for all Laravel components, and you’ll be grinning from ear to ear.

Click to share! ⬇️