Laravel 5-在服务器上使用Blade API编译字符串并进行插值 [英] Laravel 5 - Compile String and Interpolate Using Blade API on Server
问题描述
使用Blade服务容器,我想在其中包含一个带有标记的字符串并将其编译下来,以便可以将其添加到Blade模板中,并进一步进行插值.
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>
我希望将其插值到
<p>Welcome Joe,</p>
所以我可以将它作为$ content发送到Blade模板,并使其呈现所有内容和标记,因为Blade不会两次插值,现在我们的模板是客户端制作的,并存储在数据库中.
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)
会生成<p>Welcome <?php echo e($first_name); ?>,</p>
,但是我无法弄清楚如何使用Blade API在字符串中获取$ first_name解析为Joe
,并且稍后也不会在Blade模板中执行此操作.它只是在电子邮件中将其显示为带有PHP分隔符的字符串,例如:
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>
有什么建议吗?
推荐答案
这应该做到:
// 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();
}
}
用法:
$first_name = 'Joe';
$dbString = '<p>Welcome {{ $first_name }},</p>';
return CustomBladeCompiler::render($dbString, ['first_name' => $first_name]);
感谢 查看全文