appstract / laravel-blade-directives

A collection of nice Laravel Blade directives
MIT License
860 stars 75 forks source link

Added `@returnifempty` directive. #66

Open yaquawa opened 4 years ago

yaquawa commented 4 years ago

Thanks for the nice package!

I added a new @returnifempty directive. I've been using this very frequently. Hope this can be merged.

gizburdt commented 4 years ago

Hi, thanks for the PR. There is already a directive called @empty, so I think a better name would be notEmpty. Could you change it? :)

yaquawa commented 4 years ago

Hi @gizburdt, if we just call it notEmpty it seems like a normal conditional directive. But this one will return if it is empty. Directive should be self described right?

gizburdt commented 4 years ago

I talked about this with @ovanschie, but we're wondering when you would use this? It feels like logic needs to be placed inside PHP/Controller/Model and not inside Blade. Can you paste a snippet where you use this directive?

yaquawa commented 4 years ago

@gizburdt

For example, suppose you have a view component components/posts.blade

@props([
    'posts'
])

@returnIfEmpty($posts)

<section class="container">
    <h1>My Posts</h1>

    <div class="posts">
        @foreach($posts as $post)
            <div class="posts__item">{{ $post->title }}</div>
        @endforeach
    </div>
</section>

Then you can use it like this


<div>Foo</div>

{{-- if the variable $posts is empty, it got nothing to render. --}}
<x-posts :posts="$posts"/>

<div>Bar</div>

without the @returnIfEmpty, it could be written as this, which is too verbose for me.

<div>Foo</div>

@if(count($posts))
    <x-posts :posts="$posts"/>
@endif

<div>Bar</div>
yaquawa commented 4 years ago

Hi @gizburdt , would you please tell me if you are going to merge this PR in the future or not? Thanks.