How to Compile a Blade Template from a String

Render Blade from string instead of File

Hope this helps,

https://github.com/TerrePorter/StringBladeCompiler

This is a fork of the next link that removes the db model requirement and replaces it with a array that requires three required keys ('template', 'cache_key', 'updated_at') instead of the full Eloquent model.

https://github.com/Flynsarmy/laravel-db-blade-compiler

This uses a Eloquent model to get the template.

Compile Laravel blade component from string

After some digging, this was actually very easy. Laravel always delivers

$replacers = [
'x-system-status' => view('compontents.system-status', $data)->toHtml(),
];

$page = \App\Page::first();

$text = $page->content;
foreach ($replacers as $key => $value) {
$text = str_replace('{'.$key.'}', $value, $text);
}

Laravel: how to create a rendered view from a string instead of a blade file?

You can use Blade Facade.

use Illuminate\Support\Facades\Blade;

use Illuminate\Support\Facades\Blade;

public function __invoke()
{
$name='Peter Pan';
return Blade::render("
<h1> Hello {$name} </h1>
",['name'=>$name]);
}

Laravel 5 - Compile String and Interpolate Using Blade API on Server

This should do it:

// CustomBladeCompiler.php

use Symfony\Component\Debug\Exception\FatalThrowableError;

class CustomBladeCompiler
{
public static function render($string, $data)
{
$php = Blade::compileString($string);

$obLevel = ob_get_level();
ob_start();
extract($data, EXTR_SKIP);

try {
eval('?' . '>' . $php);
} catch (Exception $e) {
while (ob_get_level() > $obLevel) ob_end_clean();
throw $e;
} catch (Throwable $e) {
while (ob_get_level() > $obLevel) ob_end_clean();
throw new FatalThrowableError($e);
}

return ob_get_clean();
}
}

Usage:

$first_name = 'Joe';
$dbString = '<p>Welcome {{ $first_name }},</p>';

return CustomBladeCompiler::render($dbString, ['first_name' => $first_name]);

Thanks to @tobia on the Laracasts forums.

Render Laravel blade template as string without escaped chars and line breaks?

If you want it to be html, use method toHtml()

view('holiday.diagram')->toHtml();


Related Topics



Leave a reply



Submit