Blade Templating in Laravel: A Comprehensive Guide

Photo by Rodion Kutsaiev on Unsplash

Blade Templating in Laravel: A Comprehensive Guide

Laravel Oct 10, 2022

Laravel is a popular PHP web application framework that provides an elegant syntax for web development. One of the key features of Laravel is its built-in blade templating engine, which allows developers to easily create and manage templates for their web applications. In this article, we will take a detailed look at everything you need to know about blade templating in Laravel, including its basic concepts, functionality, and best practices.

Blade Templating Basics

Blade is a simple and lightweight templating engine that is included with Laravel by default. It allows developers to create templates using plain HTML and PHP code, without the need for a separate template language. Blade templates are stored in the "resources/views" directory of a Laravel project and use the ".blade.php" file extension.

Blade templates are processed by the Laravel framework and rendered as plain HTML, which is then sent to the browser for display. This allows developers to separate the presentation logic from the application logic, making it easy to maintain and update the look and feel of their web applications.

Blade Syntax

Blade templates use a simple and intuitive syntax that is easy to read and understand. Here are some of the key features of the Blade syntax:

  • Blade templates can include plain HTML code and PHP code, which is executed by the server before the template is rendered.
  • Blade templates use a combination of double curly braces {{ }} and @ symbols to indicate which code should be executed by the server.
  • Blade templates use a series of control structures, such as "if" and "foreach" statements, to control the flow of the template.

Blade Example

Here is a simple example of a Blade template that displays a list of items from an array:

<!DOCTYPE html>
<html>
<head>
    <title>Blade Example</title>
</head>
<body>
    <h1>Blade Example</h1>
    <ul>
        @foreach ($items as $item)
            <li>{{ $item }}</li>
        @endforeach
    </ul>
</body>
</html>

In this example, the Blade template includes a "foreach" loop that iterates over the $items array and displays each item as a list item. The PHP code is executed by the server, and the resulting HTML is sent to the browser for display.

Blade Functionality

Blade provides a range of functionality that allows developers to easily create and manage templates for their web applications. Some of the key features of Blade include:

Template Inheritance:

Blade allows developers to create a base template that can be extended by other templates. This allows developers to reuse common elements, such as headers and footers, across multiple templates.

Here's an example of how to use template inheritance in Blade:

Create a base template called "layout.blade.php" in the "resources/views" directory:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <div class="container">
        @yield('content')
    </div>
</body>
</html>

This template includes two sections, "title" and "content", that can be overridden by child templates.

Next, create a child template called "home.blade.php" in the same directory:

@extends('layout')

@section('title', 'Home')

@section('content')
    <h1>Welcome to the Homepage</h1>
    <p>This is the homepage content.</p>
@endsection

This template extends the "layout" template and overrides the "title" and "content" sections with new content.

Finally, in the controller method you can use view('home') to render the home.blade.php template which will inherit layout.blade.php

Displaying Data:

Blade makes it easy to display data in templates, using simple syntax such as {{ $variable }} to display the value of a variable.

Here's an example of how to display data in a Blade template:

In your controller method, pass data to the view:

public function show($id)
{
    $user = User::find($id);
    return view('profile', ['user' => $user]);
}

This code retrieves a user with a given ID from the database and passes it to the "profile" view as an array key 'user'.

In your "profile.blade.php" template, you can display the data using the double curly braces syntax {{ }} :

<h1>{{ $user->name }}'s Profile</h1>
<p>Email: {{ $user->email }}</p>

In this example, the template displays the name and email of the user passed from the controller method. The double curly braces {{ }} are used to output the values of the $user->name and $user->email properties.

Alternatively, you can use Blade's shorthand @ syntax to display data:

<h1>@{{ $user->name }}'s Profile</h1>
<p>Email: @{{ $user->email }}</p>

In this example, the @ symbol is used instead of the double curly braces.

It's important to note that when displaying data it's important to sanitize it properly to avoid security risks like XSS attacks. Laravel provides built-in functions such as e() or {{ }} to escape output and prevent malicious data from being executed in the browser.

Creating Components:

Blade allows developers to create reusable components, such as buttons and forms, that can be included in multiple templates.

Here's an example of how to use Blade's control structures to create a dynamic template:

In your controller method, pass a variable to the view:

public function index()
{
    $items = Item::all();
    return view('items', ['items' => $items]);
}

This code retrieves a list of items from the database and passes it to the "items" view as an array key 'items'.

In your "items.blade.php" template, you can use a Blade "foreach" loop to display the items:

<h1>Items</h1>
<ul>
    @foreach ($items as $item)
        <li>{{ $item->name }}</li>
    @endforeach
</ul>

This code uses the foreach loop to iterate over the $items array, and display the name of each item as a list item.

You can also use Blade's "if" statement to show or hide content based on certain conditions:

<h1>Items</h1>
<ul>
    @foreach ($items as $item)
        <li>{{ $item->name }}
        @if($item->is_featured)
            <span class="featured-badge">Featured</span>
        @endif
        </li>
    @endforeach
</ul>

In this example, the "if" statement checks if an item has the 'is_featured' property set to true, if it's true, it will display a "featured-badge" span.

These control structures allow developers to create dynamic templates that can display different content based on certain conditions, making it easy to create a flexible and responsive web application.

Including Views:

Blade allows developers to include other views or templates within a template, making it easy to organize and reuse code.

Here's an example of how to include views in a Blade template:

Create a new view called "header.blade.php" in the "resources/views" directory:

<header>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
</header>

This template defines a simple header navigation.

Next, in your "home.blade.php" template, you can include the "header" view using the @include directive:

@extends('layout')

@section('title', 'Home')

@section('content')
    @include('header')
    <h1>Welcome to the Homepage</h1>
    <p>This is the homepage content.</p>
@endsection

In this example, the @include directive is used to include the "header" view within the "home" template. This allows you to include the same header in multiple views without having to repeat the same code.

You can also pass data to the included view using the @include directive:

@include('header', ['title' => 'Homepage'])

This passes an array key 'title' with the value 'Homepage' to the included 'header' view.

Including views makes it easy to organize and reuse code in your templates. By breaking down your templates into smaller, reusable components, you can make your code more maintainable and easier to update.

Blade Best Practices

Blade is a powerful tool for creating and managing templates in Laravel, but it's important to follow best practices when working with it. Some of the key best practices for working with Blade include:

  • Keep templates as simple as possible: Avoid adding too much logic to templates, as this canmake them difficult to read and maintain. Instead, try to keep the templates as simple as possible and move as much logic as possible to the controller or model.
  • Use template inheritance: Take advantage of Blade's template inheritance feature to create a base template that can be extended by other templates. This makes it easy to update common elements, such as headers and footers, across multiple templates.
  • Organize templates by functionality: Create separate views for different functionality, such as displaying a list of items, creating a new item, and editing an existing item. This makes it easy to find and update templates as needed.
  • Use Blade's control structures: Blade provides a range of control structures, such as "if" and "foreach" statements, that can be used to control the flow of the template. Use these control structures to create dynamic templates that can display different content based on certain conditions.

Conclusion

Blade is a powerful and easy-to-use templating engine that is included with Laravel by default. It allows developers to create templates using plain HTML and PHP code, without the need for a separate template language. With its simple syntax, template inheritance, and range of functionality, Blade makes it easy to create and manage templates for your web applications. By following best practices and taking advantage of Blade's features, developers can create dynamic and maintainable templates that make their web applications stand out.

Tags

Anurag Deep

Logical by Mind, Creative by Heart