Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

imade's avatar
Level 12

Blade component not rendering when used conditionally

Depending on a display setting I want to render items in a grid or in a slider.
Simplified version below. This works fine when $display is 'slider' but if not, then only <div class="grid grid-cols-4 gap-4"> get rendered and nothing else. Does anyone have an idea why?

@if( $display === 'slider')
	<x-slider>
@else
	<div class="grid grid-cols-4 gap-4">
@endif

@foreach( $items as $item)
	<article>{{ $item->title }}</article>
@endforeach

@if( $display === 'slider')
	</x-slider>
@else
	</div>
@endif
0 likes
2 replies
LaryAI's avatar
Level 58

Certainly! The issue here is likely due to Blade component tags not being parsed when used directly inside Blade control structures like @if/@else. When you use <x-slider>, Blade expects matching component/parsing behavior outside of control directives for proper rendering.

Best Solution: Assign the wrapper tag to a variable, then use it only once. Alternatively, you can use Blade's @component directive, or just separate the blocks clearly.

Here's the most maintainable approach using two separate conditional blocks:

@if($display === 'slider')
    <x-slider>
        @foreach($items as $item)
            <article>{{ $item->title }}</article>
        @endforeach
    </x-slider>
@else
    <div class="grid grid-cols-4 gap-4">
        @foreach($items as $item)
            <article>{{ $item->title }}</article>
        @endforeach
    </div>
@endif

Explanation:

  • If you need to conditionally use Blade components, it's best to repeat the whole block for each case, so Blade can properly parse the component syntax and slot contents.
  • The reason your original code only renders an empty string for the grid case, is that Blade does not allow opening a component in one conditional and closing it in another—it relies on static parsing of the component tags.

Tip:
If your loop body is large and you don't want to duplicate code, consider extracting the <article> part into a separate component or use Blade includes:

{{-- resources/views/components/item-article.blade.php --}}
<article>{{ $item->title }}</article>

Then your main file becomes:

@if($display === 'slider')
    <x-slider>
        @foreach($items as $item)
            <x-item-article :item="$item" />
        @endforeach
    </x-slider>
@else
    <div class="grid grid-cols-4 gap-4">
        @foreach($items as $item)
            <x-item-article :item="$item" />
        @endforeach
    </div>
@endif

Summary:
Move the opening and closing tags for the grid or slider wrapper inside the @if...@else blocks to let Blade parse them correctly!

Please or to participate in this conversation.