Laravel 5 - 在服务器上使用 Blade API 编译字符串并进行插值 [英] Laravel 5 - Compile String and Interpolate Using Blade API on Server
问题描述
使用 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 SymfonyComponentDebugExceptionFatalThrowableError;
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]);
感谢 @tobia频道/一般讨论/render-template-from-blade-template-in-database" rel="noreferrer">Laracasts 论坛.
Thanks to @tobia on the Laracasts forums.
这篇关于Laravel 5 - 在服务器上使用 Blade API 编译字符串并进行插值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!