Complete Guide To blade Templating in laravel 5.2

IN this tutorial you learn how blade templating works in laravel 5.2 from scratch . This tutorial is best for beginners as well as for developers . Compared to most other backend languages, PHP actually functions relatively well as a templating language. But it has its shortcomings, and it’s also just ugly to be be using <?php inline all over the place, so you can expect most modern frameworks to offer a templating language.

Unlike many other Symfony-based frameworks, Laravel doesn’t use Twig by default—although there’s a Twig Bridge package that makes it easy to use Twig if you like it.

Instead, Laravel provides a custom templating engine called Blade, which is inspired by .NET’s Razor engine. It’s functionally very similar to Twig, but the syntax is closer to Razor and the learning curve for PHP developers tends to be lower than for Twig.

Take a look at a common display pattern in PHP, Twig, and Blade below

PHP vs. Twig vs. Blade
<?php /* PHP */ ?>
<?php if (empty($users)): ?>
    No users.
<?php else: ?>
    <?php foreach ($users as $user): ?>
<?= $user->first_name ?> <?= $user->last_name ?><br>
    <?php endforeach; ?>
<?php endif; ?>
{# Twig #}
{% for user in users %}
{{ user.first_name }} {{ user.last_name }}<br>
{% else %}
    No users.
{% endfor %}
{{-- Blade --}}
@forelse ($users as $user)
     {{ $user->first_name }} {{ $user->last_name }}<br>
    No users.

As you can see, Blade’s syntax tends to be somewhere between PHP and Twig—it’s more powerful, like Twig, and has convenience helpers like forelse, but its syntax is closer to PHP than Twig.

Additionally, since all Blade syntax is compiled into normal PHP code and then cached, it’s fast and it allows you to use native PHP in your Blade files if you want. The common recommendation, however, is to keep any PHP tags out of your Blade files.

Echoing data

As you can see in the examples above, {{ and }} are used to wrap sections of PHP that you’d like to echo. {{ $variable }} is similar to <?= $variable ?> in plain PHP.

It’s different in one way, however: Blade escapes all echoes by default using PHP’s htmlentities. That means {{ $variable }} is functionally equivalent to <?= htmlentities($variable) ?>. If you want to echo without the escaping, use {!! and !!} instead.

About the author

Deven Rathore

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest