Laravel 5 - Compile a string and interpolate using the Blade API on the server

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

So, I have an email line (short for short) on a server retrieved from a database:

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

And I want it to be interpolated on

<p>Welcome Joe,</p> 

Therefore, I can send it to the Blade template in the form of $ content and provide it with all the content and markup, since Blade does not interpolate twice, and now our templates are created by the client and stored in the database.

Blade::compileString(value)creates <p>Welcome <?php echo e($first_name); ?>,</p>, but I can’t figure out how to get $ first_name for a solution Joein a row using the Blade API, and this will not be done in the Blade template later. It simply displays it in a letter as a string with PHP delimiters, for example:

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

Any suggestions?

+4
source share
1 answer

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

Using:

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

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

Thanks to @tobia on the Laracasts forums .

+7
source

Source: https://habr.com/ru/post/1656423/


All Articles