Laravel 5 - 在服务器上使用 Blade API 编译字符串并进行插值

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

使用 Blade 服务容器,我想获取一个带有标记的字符串并将其编译下来,以便可以将其添加到 blade 模板中,并进一步进行插值。

所以我在服务器上有一个电子邮件字符串(为简洁起见,从以下数据库检索到):

<p>Welcome {{ $first_name }},</p>

我想将其插值到

<p>Welcome Joe,</p> 

所以我可以将它作为 $content 发送到 Blade 模板并让它呈现所有内容和标记,因为 Blade 不会插值两次,现在我们的模板是客户制作的并且存储在数据库中。

Blade::compileString(value) 生成 <p>Welcome <?php echo e($first_name); ?>,</p>,但我无法弄清楚如何使用 [=34= 使 $first_name 解析为字符串中的 Joe ] API,并且稍后不会在 Blade 模板中执行。它只是在电子邮件中将其显示为带有 PHP 分隔符的字符串,例如:

<p>Welcome <?php echo e($first_name); ?>,</p>

有什么建议吗?

应该这样做:

// 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();
    }
}

用法:

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

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

感谢@tobia on the Laracasts forums