Home Backend Development PHP Tutorial Get The Most From Blade: Laravel&#s Templating Engine

Get The Most From Blade: Laravel&#s Templating Engine

Nov 16, 2024 am 11:31 AM

What is a Templating Engine?

A templating engine is like a tool that helps you keep your content and layout separate. This makes your code cleaner and easier to manage. Instead of mixing HTML with your data, you create templates that define how your content should look, and the engine takes care of filling in the details.

What is Blade?

Blade is Laravel’s own templating engine, and it’s designed to make your life easier. Blade templates are stored in the resources/views directory, and each one has a .blade.php extension. The syntax is simple and clean, allowing you to mix HTML with PHP effortlessly. For example:

<h1>Hello, {{ $name }}!</h1>
Copy after login
Copy after login

But Blade isn’t just for displaying data. You can also add logic, like loops and conditionals, right in your templates. Here’s an example:

@if ($user)
    <p>Welcome, {{ $user->name }}!</p>
@else
    <p>Please log in.</p>
@endif
Copy after login
Copy after login

See how easy it is to show different content based on whether a user is logged in? Next time you need to loop through a list of users, try using Blade’s @foreach directive. It’s straightforward and keeps your code tidy.

Get The Most From Blade: Laravel

Template Inheritance

One of Blade’s best features is how it helps you reuse layouts. You can create a master template for your site and then just fill in the unique content for each page. Here’s a simple example:

<!-- layout.blade.php -->
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <div>



<p>This layout has placeholders (@yield) for the title and the main content. Now, let’s say you’re creating a home page. You can extend this layout like this:<br>
</p>

<pre class="brush:php;toolbar:false">@extends('layout')

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

@section('content')
    <h1>Welcome to the Home Page!</h1>
@endsection
Copy after login
Copy after login

By using @extends, you link to the layout, and @section allows you to fill in the placeholders with your specific content. This keeps your code DRY (Don’t Repeat Yourself) and super manageable. Blade simplifies your workflow, allowing you to focus more on what matters—building great web applications.

Get The Most From Blade: Laravel

Blade Components

Blade components are like little building blocks for your UI. Imagine them as Lego pieces—you create a small, reusable part of your interface and can snap it into place wherever you need it. This makes your code cleaner and more maintainable.

You can define a component once and use it throughout your application. Need a button that looks the same across different pages? Create a Blade component for it! Even better, you can pass attributes to these components to make them flexible and adaptable.

Here’s a simple example of a button component:

<!-- resources/views/components/button.blade.php -->
<button>{{ $slot }}</button>

<!-- Usage -->
<x-button>Click Me</x-button>
Copy after login
Copy after login

You can make your components dynamic by using a component class. This lets you pass in attributes like type or class to customize the button’s behavior or style.

// In a component class
public function render()
{
    return view('components.button', [
        'type' => $this->type,
        'class' => $this->class,
    ]);
}

// In the Blade component
<button type="{{ $type }}">



<h2>
  
  
  Including Subviews
</h2>

<p>Sometimes, you’ll want to break your templates into smaller pieces for better organization and reusability. Blade makes this easy with the @include directive. Think of it as a way to insert a smaller view (or subview) into a larger one.</p>

<p><img src="/static/imghw/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/173172787698773.jpg"  class="lazy" alt="Get The Most From Blade: Laravel&#s Templating Engine" /></p>

<h2>
  
  
  Blade Directives
</h2>

<p>Blade comes packed with handy directives that make common tasks a breeze. Here are a few:<br>
@csrf: CSRF token to your forms, protecting them from cross-site request forgery attacks<br>
@method: specifies the HTTP method for forms<br>
@auth: checks if a user is authenticated<br>
@guest: checks if a user is a guest (not authenticated)<br>
</p>

<pre class="brush:php;toolbar:false"><form action="/submit" method="POST">
    @csrf
    @method('PUT')
    <button type="submit">Submit</button>
</form>
Copy after login
Copy after login

Need something more customized? You can create your own Blade directives for reusable logic.

For instance, let’s say you often need to format dates. You can define a custom directive like this:

<h1>Hello, {{ $name }}!</h1>
Copy after login
Copy after login

Get The Most From Blade: Laravel

Other Features

Blade comes with some really handy features that make your life as a developer smoother. Let’s dive into a few of them.

Managing Asset URls

Need to link your CSS or JavaScript files? The asset() helper function has you covered. It generates the correct URL for your assets, so you don’t have to worry about paths:

@if ($user)
    <p>Welcome, {{ $user->name }}!</p>
@else
    <p>Please log in.</p>
@endif
Copy after login
Copy after login

Handling Empty Arrays or Collections

Blade’s @forelse directive is a lifesaver when dealing with empty arrays or collections. It lets you loop through items and also handles the case where there are no items elegantly:

<!-- layout.blade.php -->
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <div>



<p>This layout has placeholders (@yield) for the title and the main content. Now, let’s say you’re creating a home page. You can extend this layout like this:<br>
</p>

<pre class="brush:php;toolbar:false">@extends('layout')

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

@section('content')
    <h1>Welcome to the Home Page!</h1>
@endsection
Copy after login
Copy after login

Conditional Content Display

Blade offers several directives to show content based on conditions:

@isset: checks if a variable is set
@empty: checks if a variable is empty
@unless: works like if, but in reverse
Here’s an example using @isset:

<!-- resources/views/components/button.blade.php -->
<button>{{ $slot }}</button>

<!-- Usage -->
<x-button>Click Me</x-button>
Copy after login
Copy after login

Protecting Against XSS

Blade automatically escapes output to protect your app from XSS (Cross-Site Scripting) attacks. But sometimes, you might want to output raw HTML. In that case, use {!! !!}:

// In a component class
public function render()
{
    return view('components.button', [
        'type' => $this->type,
        'class' => $this->class,
    ]);
}

// In the Blade component
<button type="{{ $type }}">



<h2>
  
  
  Including Subviews
</h2>

<p>Sometimes, you’ll want to break your templates into smaller pieces for better organization and reusability. Blade makes this easy with the @include directive. Think of it as a way to insert a smaller view (or subview) into a larger one.</p>

<p><img src="/static/imghw/default1.png"  data-src="https://img.php.cn/upload/article/000/000/000/173172787698773.jpg"  class="lazy" alt="Get The Most From Blade: Laravel&#s Templating Engine" /></p>

<h2>
  
  
  Blade Directives
</h2>

<p>Blade comes packed with handy directives that make common tasks a breeze. Here are a few:<br>
@csrf: CSRF token to your forms, protecting them from cross-site request forgery attacks<br>
@method: specifies the HTTP method for forms<br>
@auth: checks if a user is authenticated<br>
@guest: checks if a user is a guest (not authenticated)<br>
</p>

<pre class="brush:php;toolbar:false"><form action="/submit" method="POST">
    @csrf
    @method('PUT')
    <button type="submit">Submit</button>
</form>
Copy after login
Copy after login

Get The Most From Blade: Laravel

Advanced use

Need to include raw HTML or JavaScript that contains Blade syntax? Use the @verbatim directive to stop Blade from trying to parse it:

// In a service provider
Blade::directive('datetime', function ($expression) {
    return "<?php echo ($expression)->format('Y-m-d H:i:s'); ?>";
});

// Usage in Blade
@datetime($dateVariable)
Copy after login

Working with APIs? Blade makes it easy to render JSON data directly in your templates:

<link rel="stylesheet" href="{{ asset('css/app.css') }}">
Copy after login

If you’re using Livewire, Blade works seamlessly with it. You can use Blade components alongside Livewire components for a dynamic, interactive UI without writing much JavaScript.

The @once directive ensures a block of code runs only one time. Blade lets you create dynamic components that adapt based on the data you pass. This is great for flexible, reusable UI pieces:

@forelse ($items as $item)
    <p>{{ $item }}</p>
@empty
    <p>No items found.</p>
@endforelse
Copy after login

The @error directive helps you show error messages for specific fields easily:

@isset($variable)
    <p>{{ $variable }}</p>
@endisset
Copy after login

When I first started using Blade, I was a little lost on how many options I have, but shortly after a whole world opened up for me. Now I can't imagine coding without it's versatile features. I hope this article helped you on finding your way into this amazing templating engine.

The above is the detailed content of Get The Most From Blade: Laravel&#s Templating Engine. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles