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

后端 未结 1 434
北海茫月
北海茫月 2020-12-10 16:39

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.

<
相关标签:
1条回答
  • 2020-12-10 17:01

    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.

    0 讨论(0)
提交回复
热议问题