Laravel - Check if @yield empty or not

Viewed 45388

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>
17 Answers

Complete simple answer

<title> Sitename.com @hasSection('title') - @yield('title') @endif </title>

I have a similar problem with the solution:

@section('bar', '')
@hasSection('bar')
<div>@yield('bar')</div>
@endif
//Output
<div></div>

The result will be the empty <div></div>

Now, my suggestion, to fix this, is

@if (View::hasSection('bar') && !empty(View::yieldContent('bar')))
<div>@yield('bar')</div>
@endif

Use View::hasSection to check if a section is defined and View::getSection to get the section contents without using the @yield Blade directive.

<title>{{ View::hasSection('title') ? View::getSection('title') . ' - App Name' : 'App Name' }}</title>

New in Laravel 7.x -- sectionMissing():

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

Check if section is missing:

@sectionMissing('name')
   @yield('alternative')
@endif

I don't think you can, but you have options, like using a view composer to always provide a $title to your views:

View::composer('*', function($view)
{
    $title = Config::get('app.title');

    $view->with('title', $title ? " - $title" : '');
});

why not pass the title as a variable View::make('home')->with('title', 'Your Title') this will make your title available in $title

Can you not do:

layout.blade.php

<title> Sitename.com @section("title") Default @show </title>

And in subtemplate.blade.php:

@extends("layout")

@section("title") My new title @stop

Sometimes you have an enclosing code, which you only want to have included in that section is not empty. For this problem I just found this solution:

@if (filled(View::yieldContent('sub-title')))
    <h2>@yield('sub-title')</h2>
@endif

The title H2 gets only displayed it the section really contains any value. Otherwise it won't be printed...

Related