
Laravel Blade Template Engine: A Beginner's Guide
Blade is Laravel's powerful and intuitive templating engine that allows you to create elegant and maintainable views. If you're new to Laravel or templating engines, this comprehensive guide will help you master Blade templates from basic syntax to advanced layouts and components.
What is Blade?
Blade is a templating engine that combines simplicity with power. It provides template inheritance, data display, conditional logic, loops, and other programming constructs while keeping your HTML clean and readable. Blade templates are compiled into plain PHP code for optimal performance.
Basic Blade Syntax
Displaying Data
Basic Output
Use the double curly braces {{ }}
to display variables:
<h1>Hello, {{ $name }}</h1>
<p>Welcome to {{ $app_name }}</p>
Escaping Output
Blade automatically escapes HTML for security:
<!-- This will escape HTML -->
{{ $user_input }}
<!-- Display raw HTML (be careful!) -->
{!! $user_input !!}
Comments
Use Blade's comment syntax:
<!-- This comment won't appear in the HTML -->
{{--
This is a multi-line comment
in Blade templates
--}}
Template Inheritance
Layouts
Creating a Layout File
Create a master layout at resources/views/layouts/app.blade.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title', 'My App')</title>
<!-- CSS -->
@section('styles')
@show
</head>
<body>
<nav>
<!-- Navigation content -->
</nav>
<div class="container">
@yield('content')
</div>
<!-- JavaScript -->
@section('scripts')
@show
</body>
</html>
Extending a Layout
Create a child view that extends the layout:
@extends('layouts.app') @section('title', 'Home Page') @section('content') <h1>Welcome to Our Website</h1> <p>This is the homepage content.</p> @endsection @section('styles') <style> .custom-style { color: blue; } </style> @endsection
Control Structures
If Statements
<?php if ($user->isAdmin()): ?>
<button>Admin Panel</button>
<?php else: ?>
<button>User Dashboard</button>
<?php endif; ?>
<!-- Inline condition -->
<button @if ($user->isActive()) class="active" @endif>Click Me</button>
Loops
For Loop
<?php for ($i = 0; $i < 5; $i++): ?>
<p>Iteration {{ $i + 1 }}</p>
<?php endfor; ?>
ForEach Loop
<ul>
<?php foreach ($users as $user): ?>
<li>{{ $user->name }}</li>
<?php endforeach; ?>
</ul>
<!-- With keys -->
<dl>
<?php foreach ($data as $key => $value): ?>
<dt>{{ $key }}</dt>
<dd>{{ $value }}</dd>
<?php endforeach; ?>
</dl>
While Loop
<?php while ($items->hasMore()): ?>
<p>{{ $items->next() }}</p>
<?php endwhile; ?>
Loops with Variables
Blade provides useful variables in loops:
<ul>
<?php foreach ($users as $index => $user): ?>
<li>
{{ $loop->index + 1 }}. {{ $user->name }}
<!-- Loop variables -->
<small>First: {{ $loop->first ? 'Yes' : 'No' }}</small>
<small>Last: {{ $loop->last ? 'Yes' : 'No' }}</small>
<small>Total: {{ $loop->count }}</small>
</li>
<?php endforeach; ?>
</ul>
Components and Slots
Creating Components
Base Component
Create a component file at resources/views/components/card.blade.php
:
<div class="card {{ $class ?? '' }}">
<div class="card-header">
{{ $title }}
</div>
<div class="card-body">
{{ $slot }}
</div>
</div>
Using Components
<x-card title="User Profile">
<p>This is the user's profile content.</p>
</x-card>
<!-- With attributes -->
<x-card title="Alert" class="alert alert-danger">
<p>This is an alert message.</p>
</x-card>
Multiple Slots
Component with Multiple Slots
<!-- resources/views/components/modal.blade.php -->
<div class="modal">
<div class="modal-header">
{{ $header }}
</div>
<div class="modal-body">
{{ $body }}
</div>
<div class="modal-footer">
{{ $footer }}
</div>
</div>
Using Multiple Slots
<x-modal>
@slot('header')
<h3>User Details</h3>
@endslot
@slot('body')
<p>User information goes here.</p>
@endslot
@slot('footer')
<button>Close</button>
@endslot
</x-modal>
Forms and URL Generation
Forms
<!-- Form with CSRF protection -->
<form action="{{ route('users.store') }}" method="POST">
@csrf
<input type="text" name="name" placeholder="Name">
<button type="submit">Save</button>
</form>
<!-- Form method spoofing -->
<form action="{{ route('users.update', $user->id) }}" method="POST">
@csrf
@method('PUT')
<input type="text" name="name" value="{{ $user->name }}">
<button type="submit">Update</button>
</form>
URL Generation
<!-- Named routes -->
<a href="{{ route('home') }}">Home</a>
<a href="{{ route('users.show', $user->id) }}">User Profile</a>
<!-- Controller actions -->
<a href="{{ action('UserController@index') }}">Users</a>
<a href="{{ action('UserController@show', $user->id) }}">User Details</a>
<!-- Asset URLs -->
<link href="{{ asset('css/style.css') }}" rel="stylesheet">
<img src="{{ asset('images/logo.png') }}" alt="Logo">
Advanced Blade Features
Include Partials
<!-- Include a partial view -->
@include('partials.header')
<!-- Include with data -->
@include('partials.card', ['title' => 'Welcome', 'content' => 'Hello World'])
Stacks
Defining Stacks
<!-- In layout -->
<head>
<title>@yield('title')</title>
@stack('styles')
</head>
<!-- In child views -->
@push('styles')
<link rel="stylesheet" href="/css/custom.css">
@endpush
Stacks vs Sections
- Sections: Override content in layouts li>Stacks: Append content to layouts
Optional Statements
<!-- Optional display -->
{{ $user->bio ?? 'No bio available' }}
<!-- Optional component -->
<?php if (isset($show_profile): ?>
@include('profile.card')
<?php endif; ?>
Performance Optimization
Caching Views
<!-- Blade templates are automatically cached -->
<!-- Clear Blade cache if needed -->
php artisan view:clear
<!-- Pre-render views for production -->
php artisan view:cache
Component Performance
- Keep components simple and focused li>Use proper slots instead of complex data passing li>Cache frequently used components
Best Practices
Keep Logic Simple
Avoid complex logic in Blade templates:
<!-- Bad: Complex logic in template -->
<?php if ($user->isAdmin() && $permission->canEdit() && $post->isEditable()): ?>
<button>Edit</button>
<?php endif; ?>
<!-- Good: Extract to method in controller -->
<button @if ($canEdit) @endif>Edit</button>
Use Meaningful Names
Use descriptive names for components and sections:
<!-- Good naming -->
<x-user-profile>
<x-button-primary>
<!-- Bad naming -->
<x-box>
<x-btn>
Accessibility Considerations
Make your templates accessible:
<!-- Use proper ARIA labels -->
<button aria-label="Close modal">×</button>
<!-- Semantic HTML -->
<main>
<article>
<section>
<!-- Content -->
</section>
</article>
</main>
Conclusion
Blade is one of Laravel's most powerful features for creating clean, maintainable, and efficient templates. By mastering Blade's syntax, inheritance, components, and advanced features, you'll build applications that are both beautiful and performant.
Remember these key takeaways:
- Use template inheritance to create reusable layouts
- Keep Blade templates clean by moving complex logic to controllers
- Leverage components for reusable UI elements
- Follow best practices for accessibility and performance
With Blade, you'll create applications that are not only functional but also a joy to work with. Start simple, practice regularly, and soon you'll be creating stunning Laravel applications!
Happy coding! 🚀