Skip to content

Instantly share code, notes, and snippets.

@MordiSacks
Last active February 14, 2022 14:32
Show Gist options
  • Save MordiSacks/23b2ae16f2f2f70e8e3d46371fe64bc0 to your computer and use it in GitHub Desktop.
Save MordiSacks/23b2ae16f2f2f70e8e3d46371fe64bc0 to your computer and use it in GitHub Desktop.
Render Blade view from string
<?php
if (!function_exists('s_view')) {
function s_view(string $id, string $template, array $data = [], array $mergeData = []): string
{
$filename = $id;
$path = storage_path('framework/tmp_blade');
View::addLocation($path);
$filepath = $path . DIRECTORY_SEPARATOR . "$filename.blade.php";
if (!file_exists($path)) mkdir($path, 0777, true);
file_put_contents($filepath, trim($template));
$vn = View::getFinder()->find(ViewName::normalize($filename));
$cached = app('blade.compiler')->getCompiledPath($vn);
try {
$rendered = (View::make($filename, $data, $mergeData))->render();
} catch (Exception $exception) {
@unlink($filepath);
@unlink($cached);
throw $exception;
}
@unlink($filepath);
@unlink($cached);
return $rendered;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment