Blade Templating
Blade templating engine in Laravel
Blade is Laravel's templating engine that provides simple and powerful syntax for creating views. Blade compiles .blade.php files and converts them to plain PHP which is cached for better performance.
Main Blade Features:
- <strong>Simple and readable syntax</strong>: Using <code>{{ }}</code> for echo and <code>@</code> for directives
- <strong>Template Inheritance</strong>: Using <code>@extends</code> and <code>@section</code> for layouts
- <strong>Components</strong>: Reusable components
- <strong>Directives</strong>: Control flow statements like <code>@if</code>, <code>@foreach</code>
- <strong>Automatic escaping</strong>: Automatic protection against XSS attacks
- <strong>Raw Output</strong>: Using <code>{!! !!}</code> for output without escaping
- <strong>Comments</strong>: Using <code>{{-- --}}</code> for comments
- <strong>Includes</strong>: Using <code>@include</code> for including partials
- <strong>Stacks</strong>: Using <code>@push</code> and <code>@stack</code> for collecting content
- <strong>Once Directive</strong>: Using <code>@once</code> for one-time execution
Common Directives:
- <code>@if</code>, <code>@elseif</code>, <code>@else</code>, <code>@endif</code> - Conditional statements
- <code>@foreach</code>, <code>@endforeach</code> - Loops
- <code>@for</code>, <code>@endfor</code> - For loops
- <code>@while</code>, <code>@endwhile</code> - While loops
- <code>@include</code> - Include partials
- <code>@extends</code> - Extend layouts
- <code>@section</code>, <code>@yield</code> - Sections
- <code>@component</code> - Components
- <code>@slot</code> - Slots
- <code>@auth</code>, <code>@guest</code> - Authentication checks
- <code>@can</code>, <code>@cannot</code> - Authorization checks
Examples
Template Inheritance
@extends('layouts.app')
@section('title', 'Users')
@section('content')
<h1>Users</h1>
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
@endsection
Using template inheritance to reuse layout.
Conditional Rendering
@if($user->isAdmin())
<p>Admin User</p>
@elseif($user->isModerator())
<p>Moderator</p>
@else
<p>Regular User</p>
@endif
@unless($user->isBanned())
<p>User is active</p>
@endunless
Using conditional statements in Blade.
Loops
@foreach($users as $user)
<p>{{ $user->name }}</p>
@if($loop->first)
<p>First user</p>
@endif
@if($loop->last)
<p>Last user</p>
@endif
@endforeach
@for($i = 0; $i < 10; $i++)
<p>Item {{ $i }}</p>
@endfor
Using loops in Blade with access to loop variables.
Includes and Partials
@include('partials.header')
@include('partials.footer', ['year' => date('Y')])
@includeIf('partials.custom', ['data' => $data])
@includeWhen($user->isAdmin(), 'partials.admin-panel')
Using @include for including partials.
Stacks
<!-- In layout -->
<head>
@stack('scripts')
</head>
<!-- In view -->
@push('scripts')
<script src="/js/custom.js"></script>
@endpush
<!-- Prepend -->
@prepend('scripts')
<script src="/js/jquery.js"></script>
@endprepend
Using stacks to collect content from multiple views.
Raw Output and Escaping
<!-- Automatic escaping (safe) -->
<p>{{ $user->name }}</p>
<!-- Raw output (dangerous - only if trusted) -->
<div>{!! $htmlContent !!}</div>
<!-- Conditional escaping -->
<p>{{ $user->bio ?? 'No bio' }}</p>
<!-- JSON encoding -->
<script>
var user = @json($user);
</script>
Difference between escaped and raw output.
Custom Directives
<?php
// In AppServiceProvider boot()
use Illuminate\Support\Facades\Blade;
Blade::directive('datetime', function ($expression) {
return "<?php echo ($expression)->format('Y-m-d H:i:s'); ?>";
});
// Usage in Blade
@datetime($user->created_at)
// Or with parameters
Blade::directive('route', function ($expression) {
return "<?php echo route($expression); ?>";
});
Creating custom directives for Blade.
Once Directive
@once
@push('scripts')
<script src="/js/analytics.js"></script>
@endpush
@endonce
<!-- This ensures the script is only added once, even if included multiple times -->
Using @once for one-time execution.
Use Cases
- Creating HTML views with simple syntax
- Template inheritance for layouts
- Reusing components
- Conditional rendering based on data
- Loops for displaying lists
- Includes for partials and reusable sections
Common Mistakes
- Using {!! !!} for untrusted data causing XSS
- Nested includes causing performance issues
- Using plain PHP instead of Blade directives
- Forgetting @endsection causing syntax errors
- Using heavy logic in Blade that should be in controller
- Not using caching causing slow rendering
Best Practices
- Always use {{ }} for output (automatic escaping)
- Use {!! !!} only for trusted HTML
- Use template inheritance for layouts
- Use components for reusable UI elements
- Keep logic in controller, not in Blade
- Use @include for partials
- Cache Blade templates
Edge Cases
- Nested loops with complex data structures
- Conditional includes with missing files
- Stacks with multiple pushes
- Custom directives with complex logic
- Blade in API responses
- Blade with very large datasets
Performance Notes
- Blade templates are compiled to PHP and cached
- First request is slower (compilation time)
- Using @include can have overhead
- Nested includes can be slow
- Blade caching in production improves performance
- Using eager loading for relationships is important
Security Notes
- Always use {{ }} for automatic XSS protection
- Use {!! !!} only for trusted HTML
- Ensure user input is always escaped
- Use @json for safe JSON encoding
- Ensure sensitive data is not exposed in views
Interview Points
- What is the difference between {{ }} and {!! !!}?
- How does template inheritance work?
- How can you create custom directive?
- What are stacks and when are they used?
- How are Blade templates cached?
- What are the benefits of using Blade?
Version Notes
- Laravel 11.x: Improved performance in Blade compilation
- Laravel 11.x: Better support for components
- Laravel 10.x: Improved @once directive
- Laravel 9.x: Improved Blade caching mechanism