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标记吗?(我不想更改视图:保护文本适用于所有其他情况).希望它足够清楚,如果不是抱歉.
截至 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)
好了,您还可以创建一个新的MailClass来扩展MailMessage
Class。
例如,您可以在 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.php
在resources/views/vendor/notifications
和追加这一点:
@if (isset($content))
<hr>
{!! $content !!}
<hr>
@endif
Run Code Online (Sandbox Code Playgroud)
我们这样做,就像一个魅力:D
如果您只想向模板添加一些基本样式,则可以在方法中使用 Markdown,而line()
无需修改任何其他代码。