【问题标题】:Store and render Laravel blade templates from the database从数据库中存储和渲染 Laravel 刀片模板
【发布时间】:2022-02-21 18:45:19
【问题描述】:

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

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

有什么想法吗?

提前致谢

【问题讨论】:

  • 这样做的目的是什么?
  • @Kyslik:允许人们管理电子邮件内容。如果刀片模板存储在数据库中,它们将能够在没有开发人员的情况下更改内容
  • @TJistooshort 你找到什么好的解决方案了吗? shopify.github.io/liquid 看起来不错,但它是用于 R&R 的,PHP 一个已经过时到最大

标签: laravel-5 laravel-blade


【解决方案1】:

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

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

$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));

【讨论】:

    【解决方案2】:

    对于那些刚刚偶然发现这一点的人:在 Laravel 9 中,它是本机实现的。

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 2018-10-03
      • 2016-07-13
      • 2016-02-27
      • 1970-01-01
      • 2016-03-17
      • 2018-08-15
      • 2015-06-04
      • 2016-11-10
      相关资源
      最近更新 更多