How do I use nl2br() in Laravel 5 Blade

前端 未结 4 1787
心在旅途
心在旅途 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:34

    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.

提交回复
热议问题