"Day 5 Lecture Notes: Mastering Laravel Blade Templating Basics"

 


Day 5 Lecture Notes
Mastering Laravel Blade Templating Basics

Objective:

  • To introduce students to Blade templating in Laravel for creating dynamic views.
  • By the end of this lesson, students should be able to use Blade to generate dynamic pages with dynamic data.

Outcome:

  • Students will understand and use the Blade templating engine to create dynamic web pages by integrating logic into views.

Introduction to Blade Templating

Laravel's Blade templating engine is a powerful and easy-to-use tool for separating logic from presentation. It allows you to create dynamic views by embedding PHP code into your HTML. Unlike traditional PHP, Blade provides a clean and concise syntax, making it easier to manage dynamic content in your web pages.

Blade files have the .blade.php extension and are typically stored in the resources/views directory of a Laravel project.


1. Blade Syntax Overview

Here are some basic concepts and Blade syntax to help you get started:

a. Blade Directives

Blade provides a range of directives (special keywords) to help you handle common tasks like conditionals, loops, and data output. Here are some commonly used directives:

1.   @if and @elseif - Conditional Statements
You can use the @if directive to conditionally display content. This is similar to PHP’s if statement.

@if($user->isAdmin())

    <p>Welcome, Admin!</p>

@elseif($user->isMember())

    <p>Welcome, Member!</p>

@else

    <p>Welcome, Guest!</p>

@endif

o    Explanation:
The @if checks a condition (e.g., if the user is an admin), and if the condition is true, the associated content is displayed. The @elseif and @else provide alternatives.

2.   @foreach - Loops
The @foreach directive is used to loop over arrays or collections. This is useful when you want to display a list of items dynamically.


@foreach($products as $product)

    <div class="product">

        <h3>{{ $product->name }}</h3>

        <p>{{ $product->description }}</p>

        <span>{{ $product->price }}</span>

    </div>

@endforeach

o    Explanation:
The @foreach loop iterates over the $products array or collection. For each item, the HTML inside the loop is repeated with the data from each product object.

3.   @yield - Content Sections
The @yield directive defines a section that can be filled by content in child views. This is useful for creating a layout file with dynamic content.

<!-- master.blade.php -->

<html>

    <head>

        <title>@yield('title')</title>

    </head>

    <body>

        <header>@yield('header')</header>

        <main>@yield('content')</main>

    </body>

</html>

o    Explanation:
In this example, @yield('title'), @yield('header'), and @yield('content') are placeholders for content that will be provided in a child view. This helps separate the structure of a page from its content.

o    Usage in a child view:

<!-- child.blade.php -->

@extends('master')

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

@section('header')

    <h1>Welcome to the Home Page!</h1>

@endsection

@section('content')

    <p>This is the content of the page.</p>

@endsection

§  Explanation:
In the child view, @extends('master') tells Blade to use the layout defined in master.blade.php. The @section directives provide the content to be inserted into the @yield placeholders in the layout.

4.   @include - Including Partial Views
The @include directive is used to include a partial view inside another view.

<!-- header.blade.php -->

<header>

    <h1>My Website</h1>

</header>

<!-- main.blade.php -->

@include('header')

<p>Welcome to my website!</p>

o    Explanation:
The @include('header') directive includes the content of header.blade.php within the main.blade.php file. This is useful for including repetitive elements like navigation menus, headers, or footers.

5.   {{ }} - Displaying Data
The curly braces {{ }} are used to output data within a Blade template. This is similar to echo in PHP but automatically escapes any HTML, preventing XSS (cross-site scripting) attacks.

<p>{{ $name }}</p>

o    Explanation:
This will safely output the value of the $name variable. Blade automatically escapes any HTML or special characters to prevent malicious code injection.


2. Using Blade for Dynamic Content

a. Dynamically Displaying Data

Using Blade, you can dynamically inject data into your views. Consider a scenario where you want to display a list of products from a database.

// In the Controller

public function showProducts()

{

    $products = Product::all();

    return view('products.index', compact('products'));

}

<!-- In the Blade View (resources/views/products/index.blade.php) -->

<h1>Product List</h1>

@foreach($products as $product)

    <div>

        <h3>{{ $product->name }}</h3>

        <p>{{ $product->description }}</p>

        <span>{{ $product->price }}</span>

    </div>

@endforeach

  • Explanation:
    In this example, the controller fetches all products from the database, and then the Blade view uses the @foreach directive to display each product dynamically. The {{ $product->name }} outputs the product's name.

b. Passing Data to Views

You can pass data to Blade views from the controller. This data can then be accessed within the view using Blade syntax.

// In the Controller

public function showWelcomePage()

{

    $name = 'John Doe';

    return view('welcome', compact('name'));

}

<!-- In the Blade View (resources/views/welcome.blade.php) -->

<h1>Welcome, {{ $name }}</h1>

  • Explanation:
    The compact('name') function passes the $name variable to the view. In the Blade view, {{ $name }} will output the value of the $name variable.

3. Practical Example: Creating a Dynamic Page

Let’s build a simple dynamic page where we display a list of users.

Step 1: Controller

public function showUsers()

{

    $users = User::all();  // Fetch all users from the database

    return view('users.index', compact('users'));  // Pass the users data to the view

}

Step 2: Blade View

<!-- resources/views/users/index.blade.php -->

@extends('layouts.app')

 

@section('title', 'User List')

 

@section('content')

    <h1>User List</h1>

    @foreach($users as $user)

        <div>

            <h3>{{ $user->name }}</h3>

            <p>Email: {{ $user->email }}</p>

        </div>

    @endforeach

@endsection

  • Explanation:
    This Blade view extends a layout (layouts.app), sets the page title with @section('title', 'User List'), and loops through the $users variable to display each user's name and email.

4. Conclusion

Blade is a powerful templating engine that allows you to cleanly separate the logic of your application from the presentation layer. By using directives like @if, @foreach, @yield, and @include, you can build dynamic views that render content based on variables, conditions, and loops.

Key Takeaways:

  • Blade files have the .blade.php extension and are stored in the resources/views directory.
  • Use directives like @if, @foreach, and @yield to manage dynamic content.
  • Blade automatically escapes output, making it secure against XSS attacks.


Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics