Laravel Blade without extra whitespace?

让人想犯罪 __ 提交于 2020-01-29 06:49:11

问题


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?

Edit: see my answer below for an updated response. There's a clean way to do this with no hacks or external libraries.


回答1:


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

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



回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/26146045/laravel-blade-without-extra-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!