Last updated 2023-08-07 04:58:16

How To Render A String As A Blade Template (Laravel 9)

Laravel 9 came with a lot of goodies and one of them is the ability to render a view from a blade template stored as a string.

This could come from a database or dynamically generated from code.

Anyways this is something you can achieve with the undocumented Blade::compileString method but requires pairing it with eval to execute the generated PHP code and then ob_start to make sure the output is captured and returned.

There is now a publicly documented method to achieve all this in one go.

01: use Illuminate\Support\Facades\Blade; 02: 03: $templateString = 'Hello, {{ $name }}'; 04: 05: return Blade::render($templateString, ['name' => 'John Doe']);

From the code above the Blade::render method has almost the same signature as the View::render method except instead of passing a blade template file name you now pass in a string template.

Cleaning up

Do note that an actual blade template file is created in the storage/framework/views directory. By default, the created file is not deleted until you clear out your cached views.

If the template structure is going to change for every render, it will be a good idea to delete them once the rendering is done. The new method allows you to pass a third parameter deleteCachedView to achieve this.

01: use Illuminate\Support\Facades\Blade; 02: 03: $templateString = 'Hello, {{ $name }}'; 04: 05: return Blade::render( 06: $templateString, 07: ['name' => 'John Doe'], 08: deleteCachedView: true 09: );

Also, note that the method minifies the generated HTML removing all whitespaces. For example, if you have a < code> tag with indented code snippets in your HTML, the indentations will be lost putting your code snippet all on one line.

Something similar to the example below.

01: use Illuminate\Support\Facades\Blade;$templateString = 'Hello, {{ $name }}';return Blade::render($templateString, ['name' => 'John Doe']);

Here is another article you might like 😊 "How To Save Command Line Outputs To A File"