简体   繁体   中英

Laravel nl2br() with sending emails

I'm using Laravel 5.3 and I'm trying to send an email with nl2br() . So I'm using the default email blade file that's new in Laravel 5.3 ( vendor/notifications/email.blade.php )

But it does not show line breaks. Only this:

sttesttesttesttesttesttesttesttesttesttesttesttest<br /> <br /> <br /> <br /> testtesttesttesttesttesttesttesttesttesttesttesttesttesttest

I've done it like this:

<!-- Outro -->
@foreach ($outroLines as $line)
    <p style="{{ $style['``'] }}">
        {{ nl2br($line) }}
    </p>
@endforeach

What am I doing wrong?

This:

{!! nl2br(htmlspecialchars($line)) !!}

is not working.

Laravel automatically escapes your string by using {{ }}

For laravel 4+ use {{{ nl2br($line) }}}

For laravel 5+ use {!! nl2br($line) !!} {!! nl2br($line) !!}

Correct me if i'm wrong on the versioning.

For Laravel 4 users:

{{ nl2br(e($message)) }}

e($x) is equivalent to {{{ $x }}} .

Laravel 5 users:

{!! nl2br(e($message)) !!}

e($x) is equivalent to {{ $x }} .

I know this is a bit late, but for everyone with the same problem. If you are using the notifications mail, new lines will not work ("\\n", "\\r", "\\r\\n").

This is because Laravel (for 5.3 and 5.4 I can confirm) strips these from the lines

vendor\\laravel\\framework\\src\\Illuminate\\Notifications\\Messages\\SimpleMessage.php

protected function formatLine($line)
{
    if (is_array($line)) {
        return implode(' ', array_map('trim', $line));
    }

    return trim(implode(' ', array_map('trim', preg_split('/\\r\\n|\\r|\\n/', $line))));
}

How I solved this is by replacing the new lines with actual html new lines <br> .

There are much better ways of doing this I'm sure, but the important part is not to overlook the formatLine function.

public function toMail($notifiable) {

    //Get your mail data
    $mail = new Email(2);
    $emailLine = $mail->getArray();

    return (new MailMessage)
        ->line(str_replace(array("\\r\\n", "\\n", "\\r","\r\n", "\n", "\r"), "<br>", $emailLine))

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM