How do I use nl2br() in Laravel 5 Blade

前端 未结 4 1706
心在旅途
心在旅途 2021-02-02 08:57

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)) !!}
4条回答
  •  臣服心动
    2021-02-02 09:47

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

提交回复
热议问题