Using Laravel, how can I modify my layout depending on whether a specific section is defined in a view?
I know I can have some default text display if the section does not exist, but imagine the following scenario:
<div class="row">
<div class="col-sm-9">
@yield('content')
</div>
<div class="col-sm-3">
@section('sidebar')
@show
</div>
</div>
So if my view defines the @section 'sidebar', this works great. But if the view doesn't define a sidebar, I don't want my main content column to be col-sm-9, I want it to be col-sm-12. I was hoping I could do something like this:
@if(@section('sidebar'))
<div class="row">
<div class="col-sm-9">
@yield('content')
</div>
<div class="col-sm-3">
@section('sidebar')
@show
</div>
</div>
@else
<div class="row">
<div class="col-sm-12">
@yield('content')
</div>
</div>
@endif
However that doesn't seem to work. Can anyone suggest an alternative?
thanks!
Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
You can use .is(':visible') selects all elements that are visible.
Check if element is visible in viewport using jquery: If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).
To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.
You can use this to tell if a section is defined or not :
@if (!empty($__env->yieldContent('sidebar')))
//It is defined
@endif
$__env->yieldContent()
returns the content of the specified section, or an empty string if it is not defined or empty.
Edit
Prior to PHP 5.5 empty()
will not work on the result of a function directly, so you can use trim()
instead, like so :
@if (trim($__env->yieldContent('sidebar')))
//It is defined
@endif
Laravel 5.2 added a @hasSection
directive that does exactly what you're asking.
It's not mentioned in 5.3 or 5.4 docs for some reason.
@hasSection('title')
<title>@yield('title') - {{ config('app.name') }}</title>
@else
<title>{{ config('app.name') }}</title>
@endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With