How do I use nl2br() in Laravel 5 Blade

核能气质少年 提交于 2019-12-31 11:37:09

问题


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?


回答1:


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('{{', '}}');



回答2:


Simple approach which works for Laravel 4 + Laravel 5.

{!! nl2br(e($task->text)) !!}



回答3:


A slightly cleaner alternative if you're using Eloquent is Mutators. On your Task model create a method like this:

public function getTextAttribute($value)
{
    return nl2br(e($value), false);
}

Now you can use {!! $task->text !!} and it will output the HTML correctly and securely. The good thing about this method is you can do all manner of conversions in the get...Attribute method, such as adding wrapper tags or using Markdown.

If you need access to both the raw data and HTML version you could replace the above with this:

public function getTextHtmlAttribute()
{
    return nl2br(e($this->text), false);
}

Then you would use {{ $task->text }} for the original and {!! $task->text_html !!} for the HTML version.



来源:https://stackoverflow.com/questions/28569955/how-do-i-use-nl2br-in-laravel-5-blade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!