Skip to content
Advertisement

Hide block in if condition

I’m a beginner

I want to make a condition under which we either hide the block or leave it, I did it and everything works

@if($postsCount < 2)
    <div class="nav" style="display: none"></div>
@else
    <div class="nav"></div>
@endif

But I am planning to add a few more blocks and everything will look like this, there will be a lot of code copying

@if($postsCount < 2)
    <div class="nav" style="display: none"></div>
    <div class="test1"></div>
    <div class="test2"></div>
    <div class="test2"></div>
    <div class="test3"></div>
    <div class="test4"></div>
@else
    <div class="nav"></div>
    <div class="test1"></div>
    <div class="test2"></div>
    <div class="test2"></div>
    <div class="test3"></div>
    <div class="test4"></div>
@endif

Can I do it somehow shorter so as not to copy the code again? development environment laravel

Advertisement

Answer

One easy way to do it is to inline it using a ternary/echo. This will give you an empty style if the post count is greater than or equal to 2, or add the display:none if it’s less.

<div class="nav" style="{{ $postsCount < 2 ? 'display: none' : ''}}"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement