
Laravel Blade Template
Blade is the templating engine used by Laravel, a popular PHP web application framework. Blade provides an elegant syntax for defining the structure and presentation of your web pages in a clean and readable way. It offers various features and directives for common tasks in web development. Here’s an overview of Laravel Blade templates:
1. Basic Output:
You can output data in Blade templates using the {{ }}
syntax:
<p>Hello, {{ $name }}!</p>
In this example, the value of the $name
variable is inserted into the HTML.
2. Escaping Output:
Blade automatically escapes output to prevent cross-site scripting (XSS) attacks. If you don’t want data to be escaped, you can use {!! !!}
:
<p>{!! $htmlContent !!}</p>
3. Comments:
You can add comments to Blade templates using the {{-- --}}
syntax:
{{-- This is a Blade template comment --}}
4. Control Structures:
Blade provides control structures like @if
, @else
, @elseif
, @foreach
, and @for
for conditional statements and loops:
@if ($user->isAdmin)
<p>Welcome, Admin!</p>
@else
<p>Welcome, User!</p>
@endif
@foreach ($items as $item)
<p>{{ $item }}</p>
@endforeach
5. Including Sub-Views:
You can include sub-views or partials using the @include
directive:
@include('partials.header')
6. Extending Layouts:
Blade allows you to create master layouts and extend them in child views using @extends
and @section
:
@extends('layouts.master')
@section('content')
<p>This is the content of the child view.</p>
@endsection
7. Yielding Content:
In a master layout, you can define sections using @yield
:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
8. Displaying Sections:
In a child view, you can provide content for sections using @section
:
@extends('layouts.master')
@section('title', 'Page Title')
@section('content')
<p>This is the content of the page.</p>
@endsection
9. Stack and Push:
Blade allows you to push content into a stack using @push
and display it later using @stack
:
@push('scripts')
<script src="/js/app.js"></script>
@endpush
...
@stack('scripts')
10. Blade Directives:
Blade provides various other directives and features, such as conditional statements (@unless
), including views conditionally (@includeIf
), and custom directives using @directive
.
These are just some of the features provided by Laravel Blade. Blade templates make it easy to create dynamic, maintainable, and readable views in your Laravel application. It encourages separation of concerns and helps you create clean and elegant templates for your web application.