DEV Community

Arif Iqbal
Arif Iqbal

Posted on • Updated on

Introduction to Blade templates in Laravel

Laravel is an MVC (Model View Controller) framework. Views separate controller/application logic from presentation logic. The Laravel views are composed of Blade templates.

Blade is a templating engine for Laravel. It was introduced in Laravel 5.1. Blade template files use the .blade.php file extension and are typically stored in the resources/views directory.

Blade makes your templates neat and clean. It increases the performance of your application by caching the template files. Blade templates are compiled to plain PHP and are cached until changed.

Blade syntax

Blade has its own syntax for writing PHP code. Here below are some examples where we translate plain PHP code to its Blade counterpart and see how Blade simplifies it.

Example 1: Displaying data

We echo value from a variable in plain PHP as

<?php echo $name; ?>
Enter fullscreen mode Exit fullscreen mode

By enabling PHP short tags we can tidy this up a little.

<?= $name ?>
Enter fullscreen mode Exit fullscreen mode

However there is still room for improvement. Let's have a look at how Blade would handle the same echo statement.

{{ $name }}
Enter fullscreen mode Exit fullscreen mode

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:

The current UNIX timestamp is {{ time() }}.
Enter fullscreen mode Exit fullscreen mode

Example 2: The PHP Ternary Operator

Before looking at the ternary operator, please note the if/ele conditional block.

if(isset($val)) {
    echo $val;
} else {
    echo "default value";
}
Enter fullscreen mode Exit fullscreen mode

We can reduce the above block of code to one statement using the ternary operator (?:). This operator is kind of a shorthand for the if/else conditional block. We use it to make sure a variable is set, or we return a default value otherwise.

In plain PHP the ternary operator is used as

<?php
echo isset($val) ? $val : "default value";
?>
Enter fullscreen mode Exit fullscreen mode

PHP 7 made it simpler by introducing the Null coalescing operator (??). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

<?php
echo $val ?? "default value";
?>
Enter fullscreen mode Exit fullscreen mode

However there is still room for improvement. Let's have a look at how Blade would handle the same echo statement.

{{ $val ?? "default value" }}
Enter fullscreen mode Exit fullscreen mode

Other examples of Blade syntax would be based on a term called Blade directives. So, let's discuss that in a separate article.

Top comments (0)