Laravel's Blade templating engine is a powerful tool that simplifies the process of building dynamic and reusable views in your web applications. With its intuitive syntax and numerous features, Blade empowers developers to create elegant and maintainable templates. In this post, we'll explore the basics of Laravel Blade templating, helping you become proficient in leveraging its capabilities.
Getting Started with Blade
Blade templates are stored in the resources/views
directory of your Laravel project. By default, Laravel provides a welcome.blade.php
file as the home page.
1.1 Blade Syntax Basics
Blade uses curly braces to denote variables and echo their values:
<h1>Hello, {{ $name }}</h1>
You can also use @
directives for more complex operations:
@if(count($users) > 0)
<ul>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
@else
<p>No users found.</p>
@endif
1.2 Extending Layouts
Blade allows you to create a master layout and extend it across multiple views:
master.blade.php
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
home.blade.php
@extends('master')
@section('title', 'Home Page')
@section('content')
<h1>Welcome to our website!</h1>
@endsection
Blade Directives
Blade offers various directives that facilitate conditional rendering, loops, and more.
2.1 Loops
Blade simplifies looping through arrays or collections:
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
2.2 Conditionals
Blade provides simple conditionals for showing or hiding content:
@if($loggedIn)
<p>Welcome back, {{ $user->name }}</p>
@else
<a href="/login">Login</a>
@endif
2.3 Includes and Stacks
Include common templates in multiple views with @include
:
@include('partials.header')
Use @stack
to define and push content to a stack:
@push('scripts')
<script src="example.js"></script>
@endpush
Blade Components (Laravel 7+)
Blade components, introduced in Laravel 7, provide reusable and self-contained UI components:
Alert.blade.php
<div class="alert alert-{{ $type }}">
{{ $slot }}
</div>
Usage in a view
<x-alert type="success">
This is a success message.
</x-alert>
Comments and Escaping
Blade supports comments:
{{-- This is a Blade comment --}}
Use double curly braces to automatically escape output:
<p>{{ $userInput }}</p>
Mastering the basics of Laravel Blade templating empowers you to create dynamic and reusable views in your Laravel applications with ease. Blade's intuitive syntax, directives, and features like extending layouts and components make it a valuable tool for building elegant UIs.