So I want to keep linebreaks from the database while using the Blade Template Engine. I came up on the idea using
{!! nl2br(e($task->text)) !!}
It works. But it looks like a needlessly complicated solution. Is there a better way?
Laravel helper provide many functionalities and you can use e Laravel helper function to purify your html before showing line breaks. You need to do the escaping first using e() and then after apply nl2br() function. {{ nl2br(e($data)) }} // OR {!! nl2br(e($data)) !!}
Laravel later introduced a great helper function __() which could be used for JSON based translations. For instance, in your blade files, {{ __('The Web Tier') }} Whereas “The Web Tier” is added in a JSON file inside of resources/lang directory i.e {locale}.json likeso, {
Comments in Blade are very simple! You can either do normal PHP comments: <? /* some comment here */ // or single line comments # or these :) ?>
You can define your own "echo format" that will be used with the regular content tags {{ ... }}
. The default format is e(%s)
(sprintf
is used to apply the formatting)
To change that format call setEchoFormat()
inside a service provider:
public function boot(){ \Blade::setEchoFormat('nl2br(e(%s))'); }
Now you can just use the normal echo tags:
{{ $task->text }}
For echos you don't want nl2br()
applied, use the triple brackets {{{ ... }}}
To switch the function of the brackets (triple and double) around, do this:
\Blade::setContentTags('{{{', '}}}'); \Blade::setEscapedContentTags('{{', '}}');
Simple approach which works for Laravel 4 + Laravel 5.
{!! nl2br(e($task->text)) !!}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With