Mastering Laravel Blade Templates

Laravel Blade Templates Example


Laravel Blade is a powerful templating engine that simplifies the process of creating dynamic views in Laravel applications. In this tutorial, we’ll cover a wide range of Blade features, from the basics to more advanced techniques, empowering you to leverage Blade effectively in your projects.

Getting Started with Blade Templates:

Blade templates in Laravel are stored in the resources/views directory. You can create a new Blade file with the .blade.php extension to start using it. Let’s create a simple Blade template called welcome.blade.php :

<!DOCTYPE html>
    <h1>Hello, {{ $name }}!</h1>

Basic Blade Directives:

Blade provides several directives to help you work with templates more efficiently. Some of the basic directives include:

  •  {{ $variable }} : Echoing variables.
  •  @if, @elseif, @else, @endif : Conditional statements.
  •  @foreach, @endforeach: Looping through arrays.
  •  @for , @endfor: Looping with a specified number of iterations.

Blade Layouts and Extending:

Blade allows you to create reusable layouts and extend them in other views. Let’s create a layout file called layout.blade.php:

<!DOCTYPE html>
    <div class="container">

You can extend this layout in other views using the @extends directive:


@section('title', 'Home Page')

    <h1>Welcome to our website!</h1>

Blade Components and Slots:

Blade components allow you to create reusable UI components. Define a component using the @component directive and render it using the @slot directive:

    @slot('type', 'success')
        This is a success message.

Using Blade Components:

Use Blade components in your views:


    <x-alert type="success">
        This is a success message.

Processing Dynamic Data in Blade Components:

Pass dynamic data to Blade components using the @props directive:

// create a component with dynamic props pre-defined like title, desc
<div class="card">
    <div class="card-header">
        {{ $title }}
        {{ $desc}}
    <div class="card-body">
        {{ $slot }}

// pass the dynamic data using props in you blade file while using the component.
<x-card :title="your-title-here" :desc="your-description-here"/>

Rendering JSON Data:

You can render JSON data directly in Blade templates using the json_encode function:

    $data = ['John', 'Doe', 'Jane', 'Smith'];

    var jsonData = {!! json_encode($data) !!};

You can get more details about this topic from here.

To get to know more about Laravel, you can check these articles too.


Mastering Laravel Blade templates opens up a world of possibilities for creating dynamic and interactive views in your Laravel applications. By understanding the basics and exploring advanced techniques, you can streamline your development process and build elegant user interfaces with ease.

Please follow and like us:

Related Posts

Leave a Reply