Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Check if @yield empty or not

Is it possible to check into a blade view if @yield have content or not?

I am trying to assign the page titles in the views:

@section("title", "hi world")

So I would like to check in the main layout view... something like:

<title> Sitename.com {{ @yield('title') ? ' - '.@yield('title') : '' }} </title>
like image 648
user2840318 Avatar asked Dec 05 '13 23:12

user2840318


3 Answers

For those looking on it now (2018+), you can use :

@hasSection('name')
   @yield('name')
@endif

See : https://laravel.com/docs/5.6/blade#control-structures

like image 100
2Fwebd Avatar answered Oct 14 '22 01:10

2Fwebd


In Laravel 5 we now have a hasSection method we can call on a View facade.

You can use View::hasSection to check if @yeild is empty or not:

<title>
    @if(View::hasSection('title'))
        @yield('title')
    @else
        Static Website Title Here
    @endif
</title>

This conditional is checking if a section with the name of title was set in our view.

 

Tip: I see a lot of new artisans set up their title sections like this:

@section('title')
Your Title Here
@stop

but you can simplify this by just passing in a default value as the second argument:

@section('title', 'Your Title Here')

 

The hasSectionmethod was added April 15, 2015.

like image 94
cborgia Avatar answered Oct 14 '22 00:10

cborgia


There is probably a prettier way to do this. But this does the trick.

@if (trim($__env->yieldContent('title')))
    <h1>@yield('title')</h1>
@endif
like image 51
Collin James Avatar answered Oct 14 '22 01:10

Collin James