gpt4 book ai didi

php - 有没有办法从字符串编译 Blade 模板?

转载 作者:IT王子 更新时间:2023-10-28 23:52:17 25 4
gpt4 key购买 nike

如何从字符串而不是 View 文件编译 Blade 模板,如下面的代码:

<?php
$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe'));
?>

http://paste.laravel.com/ujL

最佳答案

我通过扩展 BladeCompiler 找到了解决方案。

<?php namespace Laravel\Enhanced;

use Illuminate\View\Compilers\BladeCompiler as LaravelBladeCompiler;

class BladeCompiler extends LaravelBladeCompiler {

/**
* Compile blade template with passing arguments.
*
* @param string $value HTML-code including blade
* @param array $args Array of values used in blade
* @return string
*/
public function compileWiths($value, array $args = array())
{
$generated = parent::compileString($value);

ob_start() and extract($args, EXTR_SKIP);

// We'll include the view contents for parsing within a catcher
// so we can avoid any WSOD errors. If an exception occurs we
// will throw it out to the exception handler.
try
{
eval('?>'.$generated);
}

// If we caught an exception, we'll silently flush the output
// buffer so that no partially rendered views get thrown out
// to the client and confuse the user with junk.
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}

$content = ob_get_clean();

return $content;
}

}

关于php - 有没有办法从字符串编译 Blade 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16891398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com