31

以下のコードのように、ビュー ファイルではなく文字列からブレード テンプレートをコンパイルするにはどうすればよいですか。

<?php
$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe')); 
?>

http://paste.laravel.com/ujL

4

7 に答える 7

17

上記のスクリプトを少し変更します。BladeCompiler クラスを拡張せずに、この関数を任意のクラス内で使用できます。

public function bladeCompile($value, array $args = array())
{
    $generated = \Blade::compileString($value);

    ob_start() and extract($args, EXTR_SKIP);

    // We'll include the view contents for parsing within a catcher
    // so we can avoid any WSOD errors. If an exception occurs we
    // will throw it out to the exception handler.
    try
    {
        eval('?>'.$generated);
    }

    // If we caught an exception, we'll silently flush the output
    // buffer so that no partially rendered views get thrown out
    // to the client and confuse the user with junk.
    catch (\Exception $e)
    {
        ob_get_clean(); throw $e;
    }

    $content = ob_get_clean();

    return $content;
}
于 2015-11-23T13:25:45.633 に答える
1

これにまだ興味がある人のために、彼らはそれを Laravel 9 に追加しました

use Illuminate\Support\Facades\Blade;
 
return Blade::render('Hello, {{ $name }}', ['name' => 'Julian Bashir']);

https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates

于 2022-02-21T05:20:30.470 に答える