/

How to Use Blade Templates in Laravel

How to Use Blade Templates in Laravel

This tutorial is part of the Laravel Handbook. Download it from https://flaviocopes.com/access/

In Laravel, view files that end with .blade.php are Blade templates. Blade is a server-side templating language that allows you to write dynamic templates using HTML.

Blade templates offer a wide range of features to make your templates more dynamic and powerful. You can insert data, add conditionals, use loops, display content based on user authentication, and much more.

To pass data to a Blade template, you can do so in the route definition:

1
2
3
Route::get('/test', function () {
return view('test', ['name' => 'Flavio']);
});

And then you can use the data in the template like this:

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

The {{ }} syntax allows you to add any data to the template and escape it properly.

In addition to data insertion, you can also run any PHP function inside Blade templates, and Blade will display the return value of that function’s execution.

Blade templates also support comments, which can be written using {{-- --}} syntax:

1
{{-- <h1>test</h1> --}}

Blade provides conditional directives like @if, @else, and @endif to perform conditional rendering based on values. Here’s an example:

1
2
3
4
5
@if ($name === 'Flavio') 
<h1>Yo {{ $name }}</h1>
@else
<h1>Good morning {{ $name }}</h1>
@endif

Blade also offers @elseif and @unless for more complex conditional structures. There’s also @switch directive to show different content based on the result of a variable.

Blade provides shortcuts for common operations, such as @isset, @empty, @auth, @guest, and @production to make template logic more convenient and readable.

If you need to write custom PHP code in your template, you can use the @php directive:

1
2
3
@php
$cats = array("Fluffy", "Mittens", "Whiskers", "Felix");
@endphp

Blade also supports loops, which can be created using directives like @for, @foreach, and @while. Here are some examples:

1
2
3
4
5
6
7
8
9
@for ($i = 0; $i < 10; $i++)
Count: {{ $i }}
@endfor

<ul>
@foreach ($cats as $cat)
<li>{{ $cat }}</li>
@endforeach
</ul>

Blade provides additional directives like @continue and @break to control loop flow. Inside a loop, you can access the $loop variable to get information about the current iteration, such as if it’s the first or last iteration, odd or even, the number of iterations done, and the number of iterations left.

This is just a basic introduction to Blade templates. For more information, check out the official Blade guide.

tags: [“Laravel”, “Blade templates”, “server-side templating”, “PHP”, “HTML”, “conditionals”, “loops”]