Code Happy: Blade Templates

← Back to Index

Please note that this chapter was written for VERSION 3 of the Laravel PHP Framework.

Laravel's Blade templating engine will allow you to use very neat looking syntax to embed PHP code within your views. It also includes a number of short-cuts that allow a cleaner use of existing Laravel features. Blade's templates are cached by default, which makes them extremely fast!

As always, let's jump right in.

The Basics

To enable Blade templating, simply name your views with the extension .blade.php instead of .php, it's as simple as that!

When using view files with PHP frameworks, you will often find yourself using this.

<?php echo $val; ?>

By enabling PHP short tags we can tidy this up a little.

<?=$val?>

However there is still room for improvement. Let's have a look at how Blade would handle the same echo statement.

{{ $val }}

Neat! The spacing between the brackets is optional, but I think it looks better with it there. You see the contents of the double curly brackets is evaluated and echoed out. You can use any PHP you want in there, for example..

{{ 5 * time() }}

This snippet will work just as well. You see all Blade is doing, is converting {{ 5 * time() }} to <?php echo 5 * time(); ?>. Be sure to consider this if you run into any problems with blade!

Logic

What about foreach() loops? I use loads of them! I use a lot of if and else too. Blade simplifies all of these conditional statements through the use of the magical @ sign, let's take a look.

<?php

@foreach ($users as $user)
    <div class="user">{{ $user->name }}</div>
@endforeach

There, not only cleaner looking than all of those ugly PHP tags, but a lot quicker to write! What about ifs and elseifs? Well if you are used to PHP alternate syntax you will be able to guess the result. Simply replace the <?php with @ and skip the : ?> all together! What we have left is..

@if ($user->name == 'Dave')
    <p>Welcome Dave!</p>
@else
    <p>Welcome Guest!</p>
@endif

Very simple! Here are the other operators you can use with Blade, they should look familiar :

<?php

@for ($i =0; $i < 100 - 1; $i++)
    Number {{ $i }}<br />
@endfor

a standard for loop and..

{: lang="php" }

@forelse ($users as $user)
    {{ $user->name }}
@empty
    <p>There are no users.</p>
@endforelse

That last one is a little special. The forelse() statement acts as a foreach() loop, but with an extra @empty which will output the result below if the supplied array is empty (has no length). This is very handy since it avoids the need for adding an extra if statement.

Blade Layouts

Blade offers another method of writing complex or nested layouts. Using its clean syntax, this could well be the best layout implementation available within the framework. You simply have to use it to understand its beauty. Let's have a look at our primary template, which is a blade view (in this case named template.blade.php) like any other.

<!DOCTYPE HTML>
<html lang="en-GB">
<head>
    <meta charset="UTF-8">
    <title>@yield('title')</title>
</head>
<body>
    <div class="header">
        <ul>
        @section('navigation')
            <li><a href="#">Home</a></li>
            <li><a href="#">Blog</a></li>
        @yield_section
        </ul>
    </div>

    @yield('content')

</body>
</html>

Our main template uses the @yield() method to define a content region that can be filled by a view that uses this layout. Simply pass a string to the method to provide a nickname for that content region, it will then be used to identify it later.

The @section() and @yield_section are used to define a content region that will contains some default data that could be replaced at a later date. Let's have a look at a view (page.blade.php) that makes use of the template we have just created.

@layout('template')

@section('title')
Dayle's Webpage!
@endsection

@section('navigation')
    @parent
    <li><a href="#">About</a></li>
@endsection

@section('content')
    <h1>Welcome!</h1>
    <p>Welcome to Dayle's web page!</p>
@endsection

In this view we use the @layout() method to specify that we want to use a view named template that we created earlier as our layout. Now we can use @section() and @endsection to replace yielded content regions with the code found between these two methods.

In the case of the navigation section you will notice that we have a @parent stub inside the content area. Blade will replace this with the content from the base template.

If we return..

return View::make('page');

From our route/action we can now see our page, wrapped within the layout template, like so..

<!DOCTYPE HTML>
<html lang="en-GB">
<head>
    <meta charset="UTF-8">
    <title>Dayle's Webpage!</title>
</head>
<body>
    <div class="header">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </div>

    <h1>Welcome!</h1>
    <p>Welcome to Dayle's web page!</p>

</body>
</html>

Great! We can also use as many templates as we want to, they are simply normal Blade views!

What if we want to provide the @section contents from our Action/Route? Simply call the Section::inject() method with the section name, and a string representing the sections contents, for it to be injected into the view.

Route::get('/', array('do' => function()
{
    Section::inject('title', 'My Site');

    return View::make('page');
}));

and that's all! Now you can use Blade to make your views look clean and efficient, your designer will love you for it.

My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.

It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!