LoginSignup
1
0

More than 1 year has passed since last update.

Bladeで変数に入れたhtml文字列を表示させる

Posted at

LaravelではViewの表示にBladeを使っています。
普通は{{と}}で囲んで変数を記述すれば変数の内容をブラウザ表示できますが、変数にhtmlを記述しているとエスケープされてしまうのでタグの内容まで表示されてしまいます。

example.blade.php
<?php $html_text='1行目<br />2行目'; ?>
{{$html_text}}

結果

1行目<br />2行目

{{ }}はクロスサイトスクリプティングを防ぐ効果があるので便利なのですが、変数にhtmlを入れてそれを画面表示の際に反映させたい場合は、思った結果が得られないことになります。

対応策

結果から言うと以下のように記載すればOKです。

solution.blade.php
<?php $html_text='1行目<br />2行目'; ?>
{!! e($html_text) !!}
  1. e()を使うことでクロスサイトスクリプティング対策を行う
  2. {!! !!}で囲むことで変数の中身をそのまま表示する

結果

1行目
2行目

参考

1
0
1

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
1
0