Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use nl2br() in Laravel 5 Blade

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?

like image 601
ya-cha Avatar asked Feb 17 '15 19:02

ya-cha


People also ask

How do you add a line break in Laravel blade?

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)) !!}

What is __ In Laravel blade?

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, {

How do you comment out blade in Laravel?

Comments in Blade are very simple! You can either do normal PHP comments: <? /* some comment here */ // or single line comments # or these :) ?>


2 Answers

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('{{', '}}'); 
like image 102
lukasgeiter Avatar answered Oct 10 '22 16:10

lukasgeiter


Simple approach which works for Laravel 4 + Laravel 5.

{!! nl2br(e($task->text)) !!} 
like image 36
lin Avatar answered Oct 10 '22 16:10

lin