Invokable > 戻る
2021-03-19
Laravel

オンデマンドView

stack overflowに誰も意味を分かってない質問があったけどたぶんこういうことなんだろうな。
https://stackoverflow.com/questions/66707015/how-to-add-html-content-in-a-php-variable-as-its-value

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;

Route::get('/', function () {
    $html = <<<'HTML'
<!DOCTYPE html>
<html>
<head>
<style>
table{
  border: 1px solid black;
}
.lft {
    padding: 0px 80px 10px 5px;
}
td {
    border-bottom: 2px solid black;
}
</style>
</head>
<body>
<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Saurabh</td>
    <td>26</td>
  </tr>
  @foreach($student as $name => $age)
  <tr>
    <td>{{ $name }}</td>
    <td>{{ $age }}</td>
  </tr>
  @endforeach
</table>
</body>
</html>
HTML;

    $student = [
        'saurabh' => 26,
        'John'    => 20,
        'Ross'    => 30,
    ];

    Storage::put('tmp.blade.php', $html);

    $html = view()->file(Storage::path('tmp.blade.php'))
                  ->with(compact('student'))
                  ->render();

    return $html;

    // viewのまま返してもいい。質問だとhtmlが欲しいように見える。
    return view()->file(Storage::path('tmp.blade.php'))
                 ->with(compact('student'));
});

通常のview('welcome')resources/views(もしくはconfig/view.phpで設定)、
view()->file()は「読み込み可能なファイルのパス」ならなんでも使えそう。
tmpファイルを保存してそれを使う。

投稿者 Invokable
0件のコメントを読むにはログインしてください。
登録 ログイン