本文介绍了有没有办法从字符串编译刀片模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从字符串而不是视图文件编译刀片模板,如下面的代码:
How can I compile a blade template from a string rather than a view file, like the code below:
<?php
$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe'));
?>
推荐答案
我通过扩展 BladeCompiler 找到了解决方案.
I found the solution by extending BladeCompiler.
<?php namespace LaravelEnhanced;
use IlluminateViewCompilersBladeCompiler 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;
}
}
这篇关于有没有办法从字符串编译刀片模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!