Search code examples
phplaravellaravel-9

Laravel 9 Inline Blade Template Rendering; Rendering constant instead of variables


There is a new feature in Laravel 9 that allows inline blade template rending. Link: https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates

Let’s say I have a value stored in the database (as the body of the email) I want to render from database as email.

E.g <p> Dear {{$first_name}} {{$last_name}} </p>

I would use this;

Blade::render($body, [‘first_name’ => $first_name, ‘last_name’ => $last_name]);

With this I’m able to output something like;

Dear John Doe

In the body of the email sent.

However, what if I want to use <p> Dear {{first_name}} {{last_name}} </p>

in my email template stored in the database (without the dollar sign, making it a constant rather than a variable). How can I render this constant using the Blade::render()?


Solution

  • I think you will have to manipulate the templates, before sending output to blade.

    Laravel has many helpers to do things like that.

    use Illuminate\Support\Str;
     
    $string = '{{first_name}} {{last_name}}';
     
    $replaced = Str::replace('{{', '{{$', $string);
    
    // in $replaced you'll have '{{$first_name}} {{$last_name}}'
    

    Above code will do the job.