laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 31 forks source link

[Feature] Add a @returnif blade directive #2640

Open tkaravou opened 3 years ago

tkaravou commented 3 years ago

In many cases, we have Blade partials that are wrapped up in an if statement to conditionally render them. It would be nice having something like @returnif where we exit the partial right away if the criteria is met

Blade::directive('returnif', function ($expression) {
    return "<?php if($expression) return; ?>";
});

Usage

@returnif (empty($records))

<h3>Record Listing</h3>
<ul>
@foreach($records as $record)
    <li>{{ $record->name}}</li>
@endforeach
</ul>
ahinkle commented 3 years ago

Can you provide why it would be a benefit over the existing conditionals available in the framework? Your suggested implementation could cause unexpected bugs in applications with early returns.

@if (! $records)
    <h3>Record Listing</h3>
    <ul>
    @foreach($records as $record)
        <li>{{ $record->name}}</li>
    @endforeach
    </ul>
@endif

Alternatively:

<h3>Record Listing</h3>
<ul>
@forelse($records as $record)
    <li>{{ $record->name}}</li>
@empty
    <li>No records.</li>
@endforelse
</ul>