Blade: escaping text and allowing new lines
Asked Answered
E

3

60

I have a user-input text displayed on one of the pages. I want to allow new lines, though. How do I display the text, so it is escaped AND allows new lines?

I used nl2br() and Blade's tripple brackets {{{$text}}}, however, obviously, the tripple brackets escape <br/> tags as well.

Is there a way to combine escaping and HTML's new lines using Blade?

Thanks.

Evanne answered 19/1, 2015 at 14:47 Comment(0)
S
135

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

{{ nl2br(e($text)) }}

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

Step answered 19/1, 2015 at 14:53 Comment(3)
For Laravel 5, use this: {!! nl2br(e($text)) !!}Augusto
@MohitMamoria, what exactly does that do? What is wrong with {{ ... }}?Impermeable
@OliverCooper I've linked the official docs below. Basically, the default way runs anything between {{}} through htmlspecialchars to prevent XSS attacks. {!! !!} bypasses this functionality. So it must be used with care. laravel.com/docs/5.7/blade The section is titled Displaying Unescaped DataMelisent
M
83

You can use this

{!! nl2br(e($text)) !!}
Murdoch answered 21/8, 2016 at 17:42 Comment(0)
M
0

A simple approach you can use in Blade files:

{!! nl2br(e($onlineSetting->instruction)) !!} 
Mezzorilievo answered 26/2, 2020 at 20:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.