Home > database >  Laravel: how to create a rendered view from a string instead of a blade file?
Laravel: how to create a rendered view from a string instead of a blade file?

Time:06-20

I've some html with {{ soimething }} placeholders in a table.

I would like to get the rendered view from this custom html. I would like to avoid to manually do string replace. Is it possible?

Note : I seen suggested questions but I ended finding a more concise way to reach my goal. So I post an answer to this question. Please keep this open.

CodePudding user response:

You can use Blade Facade.

use Illuminate\Support\Facades\Blade;

use Illuminate\Support\Facades\Blade;

    public function __invoke()
    {
        $name='Peter Pan';
        return Blade::render("
        <h1> Hello {$name} </h1>
        ",['name'=>$name]);
    }

CodePudding user response:

Found

We can use \Illuminate\View\Compilers\BladeCompiler::render($string, $data)

Where

  • $string is the text to parse, for example Hi {{$username}}
  • $data is the same associate array we could normally pass down to view() helper, for example [ 'username' => $this->email ]

I was missing this from the official doc: https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates

So we can also use

use Illuminate\Support\Facades\Blade;

Blade::render($string, $data)

  • Related