Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use blade in blade

In my database I save texts that contains blade markup like:

Hello {!! $name !!} how are you today.

I pass this text to my email template in a variable $text. In the email I use {!! $text !!} to get the text in the mail. However when the email is send it shows the {!! signs instead of the variable (which is also passed). How can I save blade markup in my database and pass it to my code where it needs to replace {!! something !!} with the right variable?

My mail function.

$email = $order->email;
$name = $order->billingname;

 //The text From the database.
$emailText = Email::findOrFail(5);
$mailtext = $emailText->text;

Mail::send('emails.tracktrace', ['text'=>$mailtext'email' => $email, 'name' => $name],
function ($m) use ($code, $email, $name) {
    $m->from('[email protected]', 'domain');

    $m->to($email, $name)->subject('Track your package!');
});

Update

I've got a workaround where i do:

$mailtext = str_replace('[name]', $name, $mailtext);

this way the user can use [name], I would still like to know how to use it with blade only.

like image 791
Sven van den Boogaart Avatar asked Dec 12 '15 05:12

Sven van den Boogaart


Video Answer


1 Answers

You can't have a blade-string to compiled PHP code without rendering it at the first place. You should try your custom rendering class or invoke Blade.

public function send()
{
    $emailText = Email::findOrFail(5);
    $name = $order->billingname;
    $mailtext = \Blade::compileString($emailText->text);
    ob_start();
    eval("?> $mailtext <?php");
    $mailtext = ob_get_clean();
    Mail::send('emails.tracktrace', [
            'text' => $mailtext,
            'email' => $email,
            'name' => $name
        ],
        function ($m) use ($code, $email, $name) {
            $m->from('[email protected]', 'domain');
            $m->to($email, $name)->subject('Track your package!');
    });
}

However it's not safe as there is an eval. [Tested in Laravel 5.1]

Also there are some well written packages out there for this specific purpose, like StringBladeCompiler v3

like image 85
revo Avatar answered Sep 28 '22 08:09

revo