Home > database >  Hide block in if condition
Hide block in if condition

Time:11-16

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

CodePudding user response:

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>

CodePudding user response:

Just use a variable

@php
    $css_hide="";
@endphp 

@if($postsCount < 2)
    $css_hide = 'style="display: none"';

@endif
<div class="nav" {$css_hide} ></div>
    <div class="test1"></div>
    <div class="test2"></div>
    <div class="test2"></div>
    <div class="test3"></div>
    <div class="test4"></div>

CodePudding user response:

So far, from the options it is to take this code into a separate file

<div class="nav"></div>
<div class="test1"></div>
<div class="test2"></div>
<div class="test2"></div>
<div class="test3"></div>
<div class="test4"></div>

And on the page use like this

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

But I'm ready to look at other suggestions

  • Related