Laravel:通知中的HTML

rap*_*2-h 5 php notifications laravel laravel-5.3

我正在使用默认通知系统(Laravel 5.3)发送电子邮件.我想在消息中添加HTML标记.这不起作用(它以纯文本显示强标签):

public function toMail($notifiable)
{
    return (new MailMessage)
                ->subject('Info')
                ->line("Hello <strong>World</strong>")
                ->action('Voir le reporting', config('app.url'));
}
Run Code Online (Sandbox Code Playgroud)

我知道这是正常的,因为文本显示在{{ $text }}邮件通知模板中.我尝试使用与csrf_field()帮助器相同的系统:

->line( new \Illuminate\Support\HtmlString('Hello <strong>World</strong>') )
Run Code Online (Sandbox Code Playgroud)

但它不起作用:它显示为纯文本.

我可以在不更改视图的情况下发送HTML标记吗?(我不想更改视图:保护文本适用于所有其他情况).希望它足够清楚,如果不是抱歉.

Ale*_*nin 9

运行将从目录php artisan vendor:publish复制email.blade.php到的命令.resources/views/vendor/notificationsvendor

打开此视图并更改{{ $line }}{!! $line !!}两个位置.在Laravel 5.3中,这些是视图中的线条101137线条.

这将显示未转义的 line字符串,允许您在通知电子邮件中使用HTML标记.


Kou*_*Das 7

截至 2021 年 5 月,该HtmlString课程运行良好。我已经用 Laravel 7、8 做到了这一点。

试试这个,它应该可以工作

->line(new HtmlString("<b>This is bold HTML text</b>"))
Run Code Online (Sandbox Code Playgroud)

确保在顶部导入

use Illuminate\Support\HtmlString;
Run Code Online (Sandbox Code Playgroud)


Eri*_*rda 5

好了,您还可以创建一个新的MailClass来扩展MailMessageClass。

例如,您可以在 app\Notifications

<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\MailMessage;

class MailExtended extends MailMessage
{
    /**
     * The notification's data.
     *
     * @var string|null
     */
    public $viewData;

    /**
     * Set the content of the notification.
     *
     * @param string $greeting
     *
     * @return $this
     */
    public function content($content)
    {
        $this->viewData['content'] = $content;

        return $this;
    }

    /**
     * Get the data array for the mail message.
     *
     * @return array
     */
    public function data()
    {
        return array_merge($this->toArray(), $this->viewData);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的通知中使用:

代替:

return (new MailMessage())
Run Code Online (Sandbox Code Playgroud)

更改为:

return (new MailExtended())
Run Code Online (Sandbox Code Playgroud)

然后,您可以content在通知视图中使用var。例如,如果你发布的通知的意见(php artisan vendor:publish),您可以编辑email.blade.phpresources/views/vendor/notifications和追加这一点:

@if (isset($content))
<hr>
    {!! $content !!}
<hr>
@endif
Run Code Online (Sandbox Code Playgroud)

我们这样做,就像一个魅力:D


And*_*unn 5

如果您只想向模板添加一些基本样式,则可以在方法中使用 Markdown,而line()无需修改任何其他代码。

  • 所以在这种情况下 `-&gt;line("Hello **World**")` (2认同)