I try to render an data from user textarea input saved in my database.
I need to keep the line breaks use nl2br,
and also want to santize to prevent malicious script by using blade {{{ }}}.
But {{{ nl2br($output) }}} wont work, the br tag would also be sanitize.
Please give me some hint, thanks.
For Laravel 4 users:
{{ nl2br(e($message)) }}
e($x)
is equivalent to {{{ $x }}}
.
Laravel 5 users:
{!! nl2br(e($message)) !!}
e($x)
is equivalent to {{ $x }}
.
Sawny's answer is a great one that really leverages the power of the Blade syntax well, except I would take it a step further. You can use Blade::extend
to create your own Blade @
shortcodes so I use the following:
Blade::extend(function($value, $compiler)
{
$pattern = $compiler->createMatcher('nlbr');
return preg_replace($pattern, '$1<?php echo nl2br(e($2)); ?>', $value);
});
Now in your Blade template all have to do is something like this:
<div>@nlbr($sometext)</div>
EDIT: I realized someone coming across this may very well wonder, "Where do I put the Blade::extend
function?"
To be honest, it can go in a lot of places (and it depends on if you're using Laravel 4 or 5 as to the 'best' approach).
A simple place to put it is in the routes.php
or global.php
files as they will get picked up with the least effort. These are however, not the best files to put them in and you would be best off learning to create Laravel Providers.
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