Blade Template
The Blade is a powerful templating engine in a Laravel framework. The blade allows to use the templating engine easily, and it makes the syntax writing very simple. The blade templating engine provides its own structure such as conditional statements and loops. To create a blade template, you just need to create a view file and save it with a .blade.php extension instead of .php extension. The blade templates are stored in the /resources/view directory. The main advantage of using the blade template is that we can create the master template, which can be extended by other files.
Why Blade template?
Blade template is used because of the following reasons:
- Displaying data
If you want to print the value of a variable, then you can do so by simply enclosing the variable within the curly brackets.
Syntax
In blade template, we do not need to write the code between <?php echo $variable; ?>. The above syntax is equivalent to <?= $variable ?>.
- Ternary operator
In blade template, the syntax of ternary operator can be written as:
The above syntax is equivalent to <?= isset($variable) ? $variable : ?default value? ?>
Blade Template Control Statements
Blade templating engine also provides the control statements in laravel as well as shortcuts for the control statements.
Output
Blade template provides @unless directive as a conditional statement. The above code is equivalent to the following code:
@hasSection directive
The blade templating engine also provides the @hasSection directive that determines whether the specified section has any content or not.
Let’s understand through an example.
Output
Blade Loops
The blade templating engine provides loops such as @for, @endfor, @foreach, @endforeach, @while, and @endwhile directives. These directives are used to create the php loop equivalent statements.
@for loop
- First, we create the student.blade.php file in resources/views directory.
Student.blade.php
- Now, add the following code in PostController.php file.
- Add the route in the web.php file.
Output
@foreach loop
- First, we create the student.blade.php file in resources/views directory.
- Now, add the following code in the PostController.php file.
In the above code, we are passing the students array to the student.blade.php file.
- Add the route in the web.php file.
Output
@while loop
- First, we create the student.blade.php file in resources/views directory.
- Now, add the following code in PostController.php file.
- Add the route in web.php file.
Output