使用Blade服务容器我想在其中带一个带有标记的字符串并将其编译下来,以便将其添加到刀片模板中,并进一步插值。
所以我在从以下数据库中检索到的服务器上有一个电子邮件字符串(简称为abridge):
<p>Welcome {{ $first_name }},</p>
我希望它插入到
<p>Welcome Joe,</p>
所以我可以将它作为$ content发送到Blade模板并让它呈现所有内容和标记,因为Blade不会内插两次,现在我们的模板是客户端制作并存储在数据库中。
Blade::compileString(value)
生成<p>Welcome <?php echo e($first_name); ?>,</p>
,但我无法弄清楚如何使用Blade API将$ first_name解析为字符串中的Joe
,并且它不会#39} ;稍后在Blade模板中执行此操作。它只是在电子邮件中显示为带有PHP分隔符的字符串,如:
<p>Welcome <?php echo e($first_name); ?>,</p>
有什么建议吗?
答案 0 :(得分:10)
这应该这样做:
// 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]);