Citizen
Citizen

Reputation: 12957

Laravel Blade without extra whitespace?

If you do this you get an error:

<p>@if($foo)@if($bar)test@endif@endif</p>

And if you do this, you get <p> test </p>, adding too much whitepace:

<p>@if($foo) @if($bar)test@endif @endif</p>

Is there a way to avoid this?

Upvotes: 20

Views: 25611

Answers (6)

gamgamstyle
gamgamstyle

Reputation: 11

value="@error('title'){{old('title')}}@else{{''}}@isset($myBook->title){{$myBook->title}}@endisset{{''}}@enderror">

this works for me.

Upvotes: 0

Matej Hanzlić
Matej Hanzlić

Reputation: 151

You can add {{""}} in between the code you want to close or connect without space.

<p>@if($foo)@if($bar)test@endif{{""}}@endif</p>

Upvotes: 15

Citizen
Citizen

Reputation: 12957

this appears to be getting a lot of search traffic so I figured I'd add an update to share how I'm handling this these days. Basically, it's a little more code but it ends up being stupid simple and very clean:

@if($foo)
  <p>Test</p>
@elseif($bar)
  <p>Test2</p>
@else
  <p>Test3</p>
@endif

The moral of the story is when you're working with blade, don't try to cram a lot of conditionals within elements. Rather, have the result of the conditional contain the element. It's clean, easy to read, and with only a few more characters spent.

Upvotes: 10

Omran Jamal
Omran Jamal

Reputation: 409

You could always use the hedronium/spaceless-blade package on packagist to add this functionality to Blade.

Upvotes: 10

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

As far as I know there is no spaceless tag in Blade. If you want to use standard Blade tags you will have extra spaces. There is a github discussion with proposal for new tag

Upvotes: 5

Alex Quintero
Alex Quintero

Reputation: 1179

Try with a ternary operator, there is no whitespace control in Laravel

<p>{{ $foo ? ($bar ? 'test' : '') : ''}}</p>

Upvotes: 46

Related Questions