从数据库中存储和渲染Laravel刀片模板

时间:2018-01-24 18:36:57

标签: laravel-5 laravel-blade

如何从数据库渲染刀片模板(而不是使用刀片模板文件)?

我已经检查了这个Render template from blade template in database但由于某种原因没有替换模板中的变量。它发出通知:未定义变量。

有什么想法吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

一种最简单的方法是将内容存储在临时刀片文件中并进行渲染。

假设我们获取存储在数据库中的刀片字符串:

$content_from_db = "Hello {{ $user_name }} This is your message";

过程:

$filename = hash('sha1', $content_from_db);

// temp file location where this file will be uploaded
// it can easily be cleared with 'php artisan view:clear'
$file_location = storage_path('framework/views/');

// filepath with filename
$filepath = storage_path('framework/views/'.$filename.'.blade.php');

file_put_contents($filepath, $content_from_db);

// add framework location so that it won't look into resource/*
view()->addLocation($file_location);

$data = [ 'user_name' => 'John Doe' ];

$rendered_content = view($filename, $data)->render();

$rendered_content = trim(preg_replace('/\s\s+/', ' ', $rendered_content));