Respect line breaks in Laravel blade
Asked Answered
P

5

11

It is a doubt that I have tried to solve on my own using different methods, but none has given me the expected result.

The problem comes when I save a variable of type text in the database of my project. It saves it with line breaks, in fact when I try to edit it from one of my views, it respects those jumps. The problem comes when I want to show it in a blade.php view, where all the text is without any line break.

I have used different functions such as nl2br () or str_replace, and all they do is change the / n to the br tag for line breaks, and instead of applying those line breaks, write them on the screen next to the text.

I do not know if this change or modification to the variable should perhaps be executed on the server and sent to the view, instead of executing in the view {{nl2br ($ user-> proffile)}} or with str_replace.

First forgiveness for English and thanks in advance for the help

Pozzy answered 6/6, 2018 at 7:38 Comment(0)
H
24

You can do the escaping first, using e() and then apply nl2br():

{{ nl2br(e($user->proffile)) }}

e() is the function Blade uses when compiling triple brackets

For Laravel 5, use this: {!! nl2br(e($user->proffile)) !!}

Hydrotaxis answered 6/6, 2018 at 7:40 Comment(0)
G
13

Security Warning: This answer disables security features. Do not use in production!

Just {!! nl2br($user->proffile) !!}

{!! !!} instead of {{ }}.

i tested in laravel 8 blade and it worked.

Guiscard answered 7/2, 2021 at 14:5 Comment(2)
Use nl2br(e($user->proffile)) to escape user input. Works with all Laravel 8, too.Labefaction
I can't believe this outright dangerous answer got as much as 13 upvotes. HOW it's even possible?Tasha
G
12

An even better approach is to use plain css for this:

<p style="white-space: pre-wrap">{{ $text }}</p>

Displaying unescaped text using {!! ... !!} is very dangerous because it allows XSS attacks.

Gaynell answered 30/5, 2023 at 9:49 Comment(1)
simplest way! ThanksDibbrun
F
4

In laravel 5 you can use {!! nl2br(e($user->proffile)) !!} but this will show the html in the browser. Doing it this way doesn't show the HTML {!! nl2br($user->proffile) !!} Last time I used it was in laravel 5.6

Fibered answered 5/1, 2019 at 3:10 Comment(0)
C
-2

Kindly check the SPELLING of profile {{ nl2br(e($user->proffile)) }}. Sometime people do small mistake. kindly verify in your model.

Cataldo answered 6/6, 2018 at 8:45 Comment(1)
Please add this as comment not an answer. Thank youLabefaction

© 2022 - 2024 — McMap. All rights reserved.