Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 503
Citizen Avatar asked Oct 01 '14 16:10

Citizen


4 Answers

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

<p>{{ $foo ? ($bar ? 'test' : '') : ''}}</p>
like image 152
Alex Quintero Avatar answered Nov 17 '22 22:11

Alex Quintero


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

<p>@if($foo)@if($bar)test@endif{{""}}@endif</p>
like image 21
Matej Hanzlić Avatar answered Nov 17 '22 22:11

Matej Hanzlić


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.

like image 10
Citizen Avatar answered Nov 18 '22 00:11

Citizen


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

like image 9
Omran Jamal Avatar answered Nov 17 '22 23:11

Omran Jamal