Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the line breaks from user input but also sanitize in blade?

Tags:

laravel-4

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.

like image 382
wilson Liu Avatar asked Oct 31 '14 03:10

wilson Liu


2 Answers

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 }}.

like image 169
Sawny Avatar answered Oct 01 '22 11:10

Sawny


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.

like image 27
ashurexm Avatar answered Oct 01 '22 11:10

ashurexm