You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel邮件Blade视图中实现变量嵌套调用的问题

解决Laravel Mail中动态HTML内容的Blade变量解析问题

你遇到的核心问题是:从数据库读取的HTML内容里包含Blade风格的变量(比如{{ $url }}),但直接通过{!! $text !!}输出时,Laravel不会自动解析这些变量——因为Blade视图的编译是在视图加载阶段完成的,而$text是运行时才传入的字符串,没有经过Blade的编译流程。

下面是最直接且安全的解决方案,适用于Laravel 7及以上版本:

步骤1:使用Blade门面编译动态HTML

在你的邮件类中,借助Blade::render()方法,把数据库获取的HTML字符串当作Blade模板来编译,同时传入需要替换的变量。修改后的build方法如下:

use Illuminate\Support\Facades\Blade;

public function build()
{
    // 编译数据库中的HTML内容,替换其中的Blade变量
    $parsedText = Blade::render($this->parameters->text, [
        'url' => 'https://google.com',
        // 这里可以添加其他需要替换的变量
    ]);

    return $this->from('hello@test.it')
                ->view('view')
                ->with([
                    'text' => $parsedText,
                ]);
}

步骤2:保持视图输出不变

你的Blade视图不需要修改,依然用{!! $text !!}输出即可——因为此时$text已经是编译完成、变量替换后的最终HTML:

<div> {!! $text !!} </div>

注意事项

  • 安全风险:如果数据库中的HTML内容来自用户输入,一定要做好XSS防护(比如使用strip_tags过滤危险标签,或者使用Laravel的HTML净化工具),避免恶意代码注入。
  • 旧版本兼容:如果你使用的是Laravel 6及以下版本,可以用app('blade.compiler')->compileString()先编译字符串,再通过视图的renderString方法渲染,代码示例如下:
public function build()
{
    $compiler = app('blade.compiler');
    $compiledHtml = $compiler->compileString($this->parameters->text);
    
    $parsedText = view()->make('')->with([
        'url' => 'https://google.com',
    ])->renderString($compiledHtml);

    return $this->from('hello@test.it')
                ->view('view')
                ->with([
                    'text' => $parsedText,
                ]);
}

这样处理后,你邮件里的链接就会正确显示为https://google.com,而不是{{ $url }}了。

内容的提问来源于stack exchange,提问作者Luca Rossi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:22:49