LoginSignup
6
10

More than 3 years have passed since last update.

Laravel Blade で改行コードを改行タグに変換する

Last updated at Posted at 2020-10-29

概要

Laravel Blade で改行コード(\n)を改行タグ(<br>)に変換する。
共通で使えるヘルパーファイルを用意して共通のグローバル関数を作ります。

環境

  • PHP 7.4.4
  • Laravel 7.26.0

helpers.php を作成する

app/helpers.php
<?php declare(strict_types=1);

use Illuminate\Support\HtmlString;

if (! function_exists('html')) {
    /**
     * @param string $value
     * @return HtmlString
     */
    function html(string $value): HtmlString
    {
        return new HtmlString(nl2br(e($value)));
    }
}

(短くて良い感じの関数名を思いつきませんでした...)

composer.json に追記する

composer.json
    "autoload": {
        "files": [
            "app/helpers.php"
        ],
        // ...
    },

オートローダーを生成する

$ composer dump-autoload

使用方法

resources/views/*.blade.php
{{ html("<p>test\ntest</p>") }}

\n の改行コードは <br />\n と変換され、 <p></p> はただの文字列として表示されていればokです。

補足

{!! nl2br(e($value)) !!} でも同様のことが行えますが、不必要に {!! !!} のコードが使われることを避けるためです。

参考

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10