doulao1934 2017-01-05 13:21
浏览 50
已采纳

Laravel:通知中的HTML

I'm using the default notification system (Laravel 5.3) to send an email. I want to add HTML tags in message. This does not work (it displays the strong tags in plain text):

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

I know it's normal because text is displayed in {{ $text }} in the mail notification template. I tried to use the same system as in csrf_field() helper:

->line( new \Illuminate\Support\HtmlString('Hello <strong>World</strong>') )

But it does not work: it displays strong as plain text.

Can I send HTML tags without changing the view? (I don't want to change the view: protecting text is OK for all other cases). Hope it's clear enough, sorry if not.

  • 写回答

4条回答 默认 最新

  • duanba2001 2017-01-25 16:31
    关注

    Well, you can also create a new MailClass extending the MailMessage Class.

    For example you can create this class in 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);
        }
    }
    

    And then use in your notification:

    Instead:

    return (new MailMessage())
    

    Change it to:

    return (new MailExtended())
    

    And then you can use content var in your notification views. For example if you publish the notification views (php artisan vendor:publish), you can edit email.blade.php in resources/views/vendor/notifications and append this:

    @if (isset($content))
    <hr>
        {!! $content !!}
    <hr>
    @endif
    

    We do it like this and works like a charm :D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看