Hi!
You can pass a second parameter to the yield
function. From the docs (http://laravel.com/docs/templates#blade-templating):
Sometimes, such as when you are not sure if a section has been defined, you may wish to pass a default value to the @yield directive. You may pass the default value as the second argument:
@yield('section', 'Default Content');
So you can do something like
<title>My Awesome Site - @yield('title', 'since 2008')</title>
So whenever there is a title
section within your view, its content will be populated. Otherwise the default will be used (which also can be an empty string of course)
It might not be precisely what you want, but using the aforementioned second parameter you could do this:
<title>Website Name : @yield('page_title', 'Tagline goes here')</title>
EDIT: After I posted I saw your revision tobysommer
Both sounds like great suggestions but they aren't direct solution to my question.
I don't want to put a default value in case there's none, I need to know how to check if it returns something.
Still, I wasn't aware of that second parameter for @yield() so thanks a lot, I'm sure this will me anyways :)
I have encountered this similar problem before.
I end up with View composer
class MetaComposer{
public function compose($view)
{
if ( ! empty($view['title']) )
{
$view['title'] .= ' | '.$site_title;
}
else
{
$view['title'] = $site_title;
}
return $view;
}
}
You can use this in your view:
@if (array_key_exists('mySection', View::getSections()))
foo
@else
bar
@endif
I came up with a slightly icky solution to this:
@if ($__env->yieldContent('title')
@yield('title')
| My Site
@else
Welcome to my wonderful website!
@endif
I'm using this helper function in my Laravel 5 apps:
/**
* Checks whether a section has been captured yet.
*
* @param string $section
* @return bool
*/
function content_for($section)
{
return array_key_exists($section, app('view')->getSections());
}
Too much work, simply use:
@if (View::hasSection('something'))
do something
@else
do nothing
@endif
P/S: Please have a look into "vendor/laravel/framework/src/Illuminate/View/Factory.php"
It's even simpler now. Use the @hasSection
directive:
<title>
@hasSection('title')
@yield('title') - App Name
@else
App Name
@endif
</title>
Wow. Thank you, adriaanzon! Is there any way to use @hasSection in a ternary?
I have been doing this for about 2 years now and this is my implementation.
<title>@yield('body.title', 'default title') | Always here</title>
Then in my templates used
@section('body.title', 'Contact Us')
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community