Blade Templates

Introduction

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

Template Inheritance

Defining A Layout

Two of the primary benefits of using Blade are template inheritance and sections. To get started, let's take a look at a simple example. First, we will examine a "master" page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Blade view:

  1. <!-- Stored in resources/views/layouts/app.blade.php -->
  2. <html>
  3. <head>
  4. <title>App Name - @yield('title')</title>
  5. </head>
  6. <body>
  7. @section('sidebar')
  8. This is the master sidebar.
  9. @show
  10. <div class="container">
  11. @yield('content')
  12. </div>
  13. </body>
  14. </html>

As you can see, this file contains typical HTML mark-up. However, take note of the @section and @yield directives. The @section directive, as the name implies, defines a section of content, while the @yield directive is used to display the contents of a given section.

Now that we have defined a layout for our application, let's define a child page that inherits the layout.

Extending A Layout

When defining a child view, use the Blade @extends directive to specify which layout the child view should "inherit". Views which extend a Blade layout may inject content into the layout's sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

  1. <!-- Stored in resources/views/child.blade.php -->
  2. @extends('layouts.app')
  3. @section('title', 'Page Title')
  4. @section('sidebar')
  5. @parent
  6. <p>This is appended to the master sidebar.</p>
  7. @endsection
  8. @section('content')
  9. <p>This is my body content.</p>
  10. @endsection

In this example, the sidebar section is utilizing the @parent directive to append (rather than overwriting) content to the layout's sidebar. The @parent directive will be replaced by the content of the layout when the view is rendered.

Blade views may be returned from routes using the global view helper:

  1. Route::get('blade', function () {
  2. return view('child');
  3. });

Displaying Data

You may display data passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:

  1. Route::get('greeting', function () {
  2. return view('welcome', ['name' => 'Samantha']);
  3. });

You may display the contents of the name variable like so:

  1. Hello, {{ $name }}.

Of course, you are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement:

  1. The current UNIX timestamp is {{ time() }}.

{note} Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks.

Echoing Data If It Exists

Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:

  1. {{ isset($name) ? $name : 'Default' }}

However, instead of writing a ternary statement, Blade provides you with the following convenient shortcut, which will be compiled to the ternary statement above:

  1. {{ $name or 'Default' }}

In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.

Displaying Unescaped Data

By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

  1. Hello, {!! $name !!}.

{note} Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Blade & JavaScript Frameworks

Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

  1. <h1>Laravel</h1>
  2. Hello, @{{ name }}.

In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.

The @verbatim Directive

If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the @verbatim directive so that you do not have to prefix each Blade echo statement with an @ symbol:

  1. @verbatim
  2. <div class="container">
  3. Hello, {{ name }}.
  4. </div>
  5. @endverbatim

Control Structures

In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.

If Statements

You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

  1. @if (count($records) === 1)
  2. I have one record!
  3. @elseif (count($records) > 1)
  4. I have multiple records!
  5. @else
  6. I don't have any records!
  7. @endif

For convenience, Blade also provides an @unless directive:

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

Loops

In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts:

  1. @for ($i = 0; $i < 10; $i++)
  2. The current value is {{ $i }}
  3. @endfor
  4. @foreach ($users as $user)
  5. <p>This is user {{ $user->id }}</p>
  6. @endforeach
  7. @forelse ($users as $user)
  8. <li>{{ $user->name }}</li>
  9. @empty
  10. <p>No users</p>
  11. @endforelse
  12. @while (true)
  13. <p>I'm looping forever.</p>
  14. @endwhile

{tip} When looping, you may use the loop variable to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop.

When using loops you may also end the loop or skip the current iteration:

  1. @foreach ($users as $user)
  2. @if ($user->type == 1)
  3. @continue
  4. @endif
  5. <li>{{ $user->name }}</li>
  6. @if ($user->number == 5)
  7. @break
  8. @endif
  9. @endforeach

You may also include the condition with the directive declaration in one line:

  1. @foreach ($users as $user)
  2. @continue($user->type == 1)
  3. <li>{{ $user->name }}</li>
  4. @break($user->number == 5)
  5. @endforeach

The Loop Variable

When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

  1. @foreach ($users as $user)
  2. @if ($loop->first)
  3. This is the first iteration.
  4. @endif
  5. @if ($loop->last)
  6. This is the last iteration.
  7. @endif
  8. <p>This is user {{ $user->id }}</p>
  9. @endforeach

If you are in a nested loop, you may access the parent loop's $loop variable via the parent property:

  1. @foreach ($users as $user)
  2. @foreach ($user->posts as $post)
  3. @if ($loop->parent->first)
  4. This is first iteration of the parent loop.
  5. @endif
  6. @endforeach
  7. @endforeach

The $loop variable also contains a variety of other useful properties:

PropertyDescription
$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe iteration remaining in the loop.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent's loop variable.

Comments

Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:

  1. {{-- This comment will not be present in the rendered HTML --}}

PHP

In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

  1. @php
  2. //
  3. @endphp

{tip} While Blade provides this feature, using it frequently may be a signal that you have too much logic embedded within your template.

Including Sub-Views

Blade's @include directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:

  1. <div>
  2. @include('shared.errors')
  3. <form>
  4. <!-- Form Contents -->
  5. </form>
  6. </div>

Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

  1. @include('view.name', ['some' => 'data'])

Of course, if you attempt to @include a view which does not exist, Laravel will throw an error. If you would like to include a view that may or may not be present, you should use the @includeIf directive:

  1. @includeIf('view.name', ['some' => 'data'])

{note} You should avoid using the DIR and FILE constants in your Blade views, since they will refer to the location of the cached, compiled view.

Rendering Views For Collections

You may combine loops and includes into one line with Blade's @each directive:

  1. @each('view.name', $jobs, 'job')

The first argument is the view partial to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of jobs, typically you will want to access each job as a job variable within your view partial. The key for the current iteration will be available as the key variable within your view partial.

You may also pass a fourth argument to the @each directive. This argument determines the view that will be rendered if the given array is empty.

  1. @each('view.name', $jobs, 'job', 'view.empty')

Stacks

Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:

  1. @push('scripts')
  2. <script src="/example.js"></script>
  3. @endpush

You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:

  1. <head>
  2. <!-- Head Contents -->
  3. @stack('scripts')
  4. </head>

Service Injection

The @inject directive may be used to retrieve a service from the Laravel service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:

  1. @inject('metrics', 'App\Services\MetricsService')
  2. <div>
  3. Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
  4. </div>

Extending Blade

Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

The following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\Blade;
  4. use Illuminate\Support\ServiceProvider;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Perform post-registration booting of services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. Blade::directive('datetime', function ($expression) {
  15. return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
  16. });
  17. }
  18. /**
  19. * Register bindings in the container.
  20. *
  21. * @return void
  22. */
  23. public function register()
  24. {
  25. //
  26. }
  27. }

As you can see, we will chain the format method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:

  1. <?php echo ($var)->format('m/d/Y H:i'); ?>

{note} After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using the view:clear Artisan command.