Topics Blade Templating Slots & Dynamic Content
intermediate 14 min read

Slots & Dynamic Content

Named slots, inline component attributes, dynamic rendering, and Blade fragments in Laravel 13.

Named Slots

{{-- resources/views/components/card.blade.php --}}
<div class="card">
<div class="card-header">
{{ $title }}
</div>
<div class="card-body">
{{ $slot }}
</div>
@isset($footer)
<div class="card-footer">
{{ $footer }}
</div>
@endisset
</div>

{{-- Usage with named slots --}}
<x-card>
<x-slot:title>
<h2>User Profile</h2>
</x-slot:title>
<p>Name: {{ $user->name }}</p>
<p>Email: {{ $user->email }}</p>
<x-slot:footer>
<a href="/edit">Edit</a>
</x-slot:footer>
</x-card>

Attribute Bundles & Merging

{{-- Component with attribute merging --}}
<button {{ $attributes->merge(["type" => "button", "class" => "btn btn-".($variant ?? "primary")]) }}>
{{ $slot }}
</button>

Blade Fragments (Laravel 13)

{{-- @fragment directive for partial updates via Livewire or AJAX --}}
@fragment("user-list")
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
@endfragment

Dynamic Rendering

// Render Blade from a string (Laravel 13)
use Illuminate\Support\Facades\Blade;

$html = Blade::render("<h1>{{ \$title }}</h1>", ["title" => "Hello"]);

// Render a component class to string
$html = Blade::renderComponent(new Alert("success", "Done!"));

Examples

<?php
// Render a Blade string with variables
use Illuminate\Support\Facades\Blade;

\$rendered = Blade::render(
    '<x-alert type="success">{{ \$message }}</x-alert>',
    ['message' => 'Operation completed!']
);

echo \$rendered;

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.