Blade Template - Laravel Blade Template
Blade is a simple templating engine that helps you to create reusable templates for your Laravel application. It is a preprocessor that compiles your templates into PHP code, which is then executed by the server. In this article, we'll explore the Blade template engine in Laravel.
Syntax
The Blade syntax uses double curly braces ({{ }}
) to print variables and values, and the @
symbol to indicate control structures, such as loops and conditionals.
Printing Variables
{{ $variable }}
Control Structures
@if (condition)
// code here
@endif
@foreach ($items as $item)
// code here
@endforeach
@forelse ($items as $item)
// code here
@empty
// code if items array is empty
@endforelse
@switch($type)
@case(1)
// code if type is 1
@break
@case(2)
// code if type is 2
@break
@default
// code if type is something else
@endswitch
Blade Layouts
// app.blade.php
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
// home.blade.php
@extends('layouts.app')
@section('title', 'Home')
@section('content')
<h1>Welcome to the Home Page</h1>
@endsection
Example
Let's say we have a variable $name
and we want to print it in a Blade template.
<!-- welcome.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello, {{ $name }}!</h1>
</body>
</html>
Output
The rendered output of this Blade template would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello, John!</h1>
</body>
</html>
Assuming $name
is set to 'John'
.
Explanation
In the example above, we used the Blade syntax {{ $name }}
to print the value of the $name
variable. When the Blade template is compiled, it will be replaced with the PHP code <?php echo $name; ?>
which will then be executed by the server and output the value of $name
.
Use
Blade templates are used to create reusable templates for your Laravel application. This makes it easier to maintain your application's design and structure, as well as reducing the amount of duplicate code you need to write.
Important Points
- Blade is a simple templating engine for Laravel.
- Blade uses
{{ }}
to print variables and values, and@
symbols for control structures. - Blade templates can be extended to create reusable layouts.
- Blade templates make it easier to maintain your application's design and structure.
Summary
In this article, we explored the Blade template engine in Laravel. We learned about its syntax for printing variables and values, as well as creating control structures such as loops and conditionals. We also saw how Blade templates can be extended to create reusable layouts. Blade templates are a powerful tool in Laravel that can make your web application development more efficient and maintainable.