Blade Templates

Updated on Jul 11, 2024

As we mentioned before, Laravel's template engine is Blade. That does not mean you can't use plain PHP for your Views, though, if that is what you prefer. In our overview of Laravel, we touched upon Blade, but it is time to elaborate on it. 

Firstly, no special method or command exists to create a Blade template. To create one, simply create a View file, but instead of adding the .php file extension, you add .blade.php. The file goes in the same directory as all other Views: resources/views

Secondly, and more importantly, Blade offers several major web development advantages compared to plain PHP. Here they are.

This post includes:

section

Simplified Syntax

Probably one of its best features is Blade's ability to make writing PHP code more straightforward. It accomplishes this by providing users with shortcuts for common PHP functions and constructs, drastically reducing code bloat. Blade also makes reading the code much more convenient and easy. Below, we will provide you with two examples that perfectly portray the difference between plain PHP and Blade code.

Firstly, plain PHP:

<?php if($condition): ?>
   <p>This is true.</p>
<?php else: ?>
    <p>This is false.</p>
<?php endif; ?>

And now the simplified Blade syntax:

 
@if($condition)
     <p>This is true.</p>
@else
     <p>This is false.</p>
@endif

As you can see, the Blade syntax doesn't need the <php> tags everywhere, and the code generally looks cleaner. Another prime example is echoing values.

PHP code:

<p><?php echo $variable; ?></p>

Blade syntax:

<p>{{ $variable }}</p>

Again, as you can see, the code is much neater. To echo a variable, you just need to put it inside twin curly brackets instead of writing the tag around it.

Another example of Blade's simplified syntax is conditional statements and loops, which use the @if, @else, @elseif, @foreach, @for, and @while directives. You are probably familiar with these types of statements: if a variable is met, then perform this action, and if not, then perform the other action, for example. Here is an example that should clear everything up.

Plain PHP:

<?php
$condition = true;
if ($condition) {
    echo "<p>This is true.</p>";
} else {
    echo "<p>This is false.</p>";
}
?>

Blade syntax:

@if($condition)
    <p>This is true.</p>
@else
    <p>This is false.</p>
@endif

In the examples, we have the $condition variable set to true. The conditional statement itself will check if the condition is true and will generate a response depending on that outcome. You can see for yourself that the Blade syntax is much more concise and straightforward, lacking the typical <php> tags. The formatting is also much easier to read, making using Blade much more convenient.

section

Template Inheritance

Another prominent feature of Blade is the ability to create a master template, allowing you to use vast amounts of code instead of having to write it all the time. A master template can be used to outline common View structures in your application (like its pages, for instance), and then use child templates to model the specific functionality of each structure. As you can imagine, that saves time, promotes code reusability, and keeps your code consistent throughout the application. 

Creating master and child templates is as easy as creating any other Blade template: create your files in the resources/views directory and add blade.php to their names. Once the files have been created, it is time to write the templates themselves. Below is a basic example of a master and child template and how to make them work together. For our purposes, we have named the templates master.blade.php and child.blade.php. You can call them anything you wish, but make sure the names are descriptive enough at a glance. Firstly, the master template.

<!-- master.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
</head>
<body>
    <header>
        <!-- Common header content -->
    </header>
    <div class="content">
        @yield('content')
    </div>
    <footer>
        <!-- Common footer content -->
    </footer>
</body>
</html>

You can probably already understand most of this code just by looking at it. It is just a View with some extra bits. This will be the foundation of all the pages in your application. All the child templates will use this and only insert their own variables where necessary. You may have noticed a @yield directive placed several times within the HTML code. That is really the only difference between this template and the View we created earlier in this tutorial regarding its code. This directive defines a section in the master template with which child templates can interact. In other words, child templates can inject their own content only in places where the @yield directive is present. It is a placeholder for content. In our example, the title and content of the page are open for child templates to insert content.

Speaking of child templates, here is an example of one that interacts with the master template.

<!-- child.blade.php -->
@extends('layouts.master')
@section('title', 'Page Title')
@section('content')
    <p>This is the specific content for the child page.</p>
@endsection

As before, there are two directives here: @extends and @section. The @extends directive basically tells the application which template to use as its foundation. In our case, it is the one called master. Meanwhile, the @section directive defines the part of the code where the child theme will insert its own content. It is the other side of the @yield coin. When rendered, the child template will look like this.

<!-- Rendered Output -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Title</title>
</head>
<body>
    <header>
        <!-- Common header content -->
    </header>
    <div class="content">
        <p>This is the specific content for the child page.</p>
    </div>
    <footer>
        <!-- Common footer content -->
    </footer>
</body>
</html>

We have bolded the sections where the child template injects its specific content. We are certain you can understand how convenient template inheritance is now. You don't have to save the master template on some random file on your computer anymore and paste it every time you need it. It is all in your application and ready to be used.

section

Components and Custom Directives

The final two significant features of Blade we will mention are its ability to create reusable components for Views and custom directives. 

Components

Firstly, let's take a look at the reusable components you can create with Blade. What is a component, though?

Simply put, a component encapsulates a specific functionality of a View. It is a block of code you can insert into any View to give it new functionality. Imagine WordPress plugins but without the neat graphical interface. Nonetheless, their usefulness is undeniable, graphical interface or not, and we will show you an example of how to create one. 

Each Component consists of a class and a View file. Those files hold the HTML code of the Component and its associated logic. To begin, we will create the class file. For our example, we will call it Alert.php and place it in the app/View/Components directory. This class will extend the IlluminateViewComponent class, which defines the behavioral logic of components. Once the file is created, put this code within it.

namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
    public $type;
    public function __construct($type)
    {
        $this->type = $type;
    }
    public function render()
    {
        return view('components.alert');
    }
}

Let's break it down line by line, and you will see how easy it is to understand what is happening.

  • namespace App\View\Components; - This defines the namespace of the class. Basically, it tells the application where the Alert class resides. This way, there can be no mix-up in the application if there is another Alert class;
  • use Illuminate\View\Component; and class Alert extends Component - These lines will tell the application that this is a Blade component;
  • public $type; - Next up, this line makes this type of Component publicly accessible. In other words, users other than the admin (external users) can modify it;
  • public function __construct($type) and $this->type = $type; - These two lines are directly linked to the previous one. They trigger when the application activates the Alert component, and the $type parameter must be provided to the __construct method. Once that happens, the second line initializes the $type property with the value provided earlier: public;

public function render() and return view('components.alert'); - Finally, we have the render method. In this case, it points to the file we created earlier: the Alert component. It is important to specify the render method so that the application knows which View to use when rendering the Component.

Now that the class is created it is time to actually make the Component itself. As with all other Blade elements, it is created as a View. We will call the file alert.blade.php and place it in the resources/views/components directory. Then, write this code in it.

<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

We will use the $slot variable as a placeholder for the content that will be passed into the Component when it is used. To add this Component to a View add this code to it.

<!-- resources/views/welcome.blade.php -->
<x-alert type="success">
    This is a success message.
</x-alert>

The x-alert tag is an HTML tag that corresponds to the Alert component. As you can see, creating and setting attributes up is not difficult. It is just another piece that adds to the modularity of Blade templates.

Custom Directives

Finally, let's discuss custom directives. As the name suggests, these directives are manually created by the user and do not come with the default Laravel installation. This allows users to create custom logic for their Views in case the default one from Laravel is not sufficient. Creating a custom directive is very easy and can be done directly in a component or a View. 

That can be done by using the directive method, which comes by default with Blade. The method must be provided with two arguments: the directive's name and a closure or a callback function that defines the directive's behavior. For instance:

use Illuminate\Support\Facades\Blade;
Blade::directive('customDirective', function ($expression) {
    return "<?php // Your custom directive logic here ?>";
});

In the example above, customDirective is the name, and after it is the function with its output. You can also specify parameters within the curly braces, too. While not as powerful or widely used as the other Blade features, these custom directives can come in handy when what you are working with is not enough.

On this page...