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

旧街凉风 提交于 2019-12-18 05:59:13

问题


Using the Blade service container I want to take a string with markers in it and compile it down so it can be added to the blade template, and further interpolated.

So I have an email string (abridge for brevity) on the server retrieved from the database of:

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

And I want it to interpolated to

<p>Welcome Joe,</p> 

So I can send it to a Blade template as $content and have it render all the content and markup since Blade doesn't interpolate twice and right now our templates are client made and stored in the database.

Blade::compileString(value) produces <p>Welcome <?php echo e($first_name); ?>,</p>, but I can't figure out how to get $first_name to resolve to Joe in the string using the Blade API, and it doesn't do it within the Blade template later. It just displays it in the email as a string with PHP delimiters like:

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

Any suggestions?


回答1:


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.



来源:https://stackoverflow.com/questions/39801582/laravel-5-compile-string-and-interpolate-using-blade-api-on-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!