Using Blade in Laravel 4

When you think of Views in the Model-View-Controller pattern, you often immediately think that the View will only ever be concerned with how the page is presented to the end user. Whilst this idealistic outlook works in theory, it is rarely the case when you actually begin creating an application.

Despite the best of intentions, there is usually at least some logic code that will be required to be placed in the View. What’s more, we usually also have to stitch our Views together using partials, and so we need to be able to include other files or extend a particular view without having to create an entirely new set of files.

View template engines have become popular over the last couple of years and have been adopted by a wide array of languages and frameworks. Laravel ships with the Blade template engine, but you are of course free to switch it out for your desired tempting engine from the PHP community.

In this tutorial I’m going to introduce template engines, show you what Blade is capable of and show you how easy it is to switch to a different tempting engine if you so wish.

Why use a template engine?

So why would you want to use a template engine in the first place? If you are new to template engines, you might be thinking, what advantage could it possibly give you over raw PHP?

Well the honest answer is not a lot really. Template engines are fantastic for reducing or simplifying the code that you write in your View.

So instead of this:

<ul>  
<?php foreach $users as $user : ?>  
<li><?php echo $user->name; ?></li>  
<?php endforeach; ?>  
</ul>  

You can simply write:

<ul>  
@foreach ($users as $user)  
<li>{{ $user->name }}</li>  
@endforeach  
</ul>  

As you can see, this is a much cleaner syntax.

However, this does raise a couple of valid concerns.

Firstly it will require you to learn a new syntax for each template engine you wish to use. This is usually a hybrid of PHP and HTML.

Secondly, support for syntax highlighting in your text editor of choice might be patchy which is only going to make things harder for you.

And thirdly, using a template engine will add weight to your codebase as it must be converted into real code using the engine. Whilst this might only be a concern in certain circumstances, it is still something to think about.

Template engines aren’t a magic solution for separating your logic from your views. If you are questioning whether certain logic should be in the view, it’s probably a sign that it shouldn’t.

With all that said, I still prefer to use tempting engines because PHP is ugly and it looks disgusting in HTML.

So let’s look at Blade!

Blade

The Blade engine basically allows you to do six things:

  1. Define sections
  2. Extend views
  3. Echo and escaping
  4. Ifs
  5. Loops
  6. Includes

Define sections

The first thing you are going to want to do is to create a layout file. This file contains your header and footer code and also your defined areas such content or sidebar.

So create a file under app/views/layouts called master.blade.php and copy the following:

  
  
<nav class="navigation">  
@section(‘navigation’)  
<a href="/">Home</a>  
<a href="/about">About</a>  
@show  
</nav>

<div class="container">  
@yield(‘content’)  
</div>

<div class="sidebar">  
@yield(‘sidebar’)  
</div>  
  
  

This template has basically two different type of sections. First is the navigation section which contains the main links that will be on each page. If we needed to overwrite the navigation with page specific links, we could do that very easily with Blade.

Second we have areas where we yield the content from a partial. So the content would appear in the content section and the sidebar would appear in the sidebar section.

Extend views

To extend a View you simply have to define that this is an extension and then overwrite or append to the sections that you have defined:

@extends(‘layouts.master’)

@section(‘content’)  
<p>This will be overwritten</p>  
@stop

@section(‘sidebar’)  
@parent

<a href="#">Section specific links</a>  
@stop  

Echo and escaping

One of my favourite features of template engines is that it allows you to very easily echo or escape variables into your views.

So instead of writing:

<h1>Hello <?php echo $name; ?>!</h1>  

You can simply write:

<h1>Hello {{ $name }}</h1>  

Whenever you are printing content that has been inputted by a user you should always escape it to prevent malicious injection. You can do this very easily in Laravel by simply using 3 curly brackets:

<p>{{{ $user_input }}}</p>  

Ifs

At some point in your application, you are more than likely going to have to include some logic If statements. This is unfortunate, but it can be made cleaner by using Blade’s syntax:

@if (count($friends) === 1)  
You have one friend  
@elseif (count($friends) > 1)  
You have {{ count($friends) }} friends  
@else  
You don’t have any friends  
@endif  

Another useful bit of Blade logic is the unless block:

@unless (Auth::check())  
You are not signed in.  
@endunless  

In this example I’m simply checking to see if the user is logged in.

Loops

Loops are another common bit of logic that you might be required to implement in your view. This is usually the case when you need to iterate through an array of results to display each one:

For:

@for ($i = 1; $i < 100; $i++)  
<li>{{ $i }} … </li>  
@endfor  

Foreach:

@foreach ($users as $user)  
<li>This is user {{ $user->name }}</li>  
@endforeach  

While:

@while (true)  
<p>I have no good reason to use this.</p>  
@endwhile  

Includes

Finally, to include views in other views you can simply use the include tag:

@include(‘view.name’)  

This is useful if you want to use partials. So for example, you could save your navigation into a partial and simply include it into the template whenever you needed it.

Using other engines

Another popular template engine is Twig. Using this Github repo, we can very easily install Twig through Composer.

To install Twig, add the following to your composer.json file:

{  
"require": {  
"rcrowe/twigbridge": "0.4.*"  
}  
}  

Next add the following to your providers array in app/config/app.php:

‘TwigBridge\TwigServiceProvider’  

Now you have full access to the fantastic Twig template engine!

Conclusion

Whilst using a template engine won’t solve all of your View logic problems, it will make any logic that you are required to include in your views a lot cleaner. Template engines also allow you to easily create layouts, extend them and include partials to prevent you repeating the same HTML in multiple files.

Overall I think template engines are really good and definitely worth the little bit of extra time it will take to learn the syntax of a new one. If you happen to be working with a front end coder who isn’t comfortable using PHP, the syntax is usually a lot easier to pick up.

This has been a brief overview of using Blade in Laravel 4 and a quick introduction to each of the elements. However, to really see them in action, keep following a long with this series as I get into building the front end of Cribbb!

This is a series of posts on building an entire Open Source application called Cribbb. All of the tutorials will be free to web, and all of the code is available on GitHub.

To view a full listing of the tutorials in this series, click here.

Using Blade in Laravel 4
Share this