I'm using Laravel 9 and running PHP 8.2.
In blade views I can use the following example blade component:
<x-frontend.module-button href="#" text="Example button" />
But when using a HEREDOC like so:
$html = <<<HTML
<x-frontend.module-button href="#" text="This will not output anything" />
HTML;
The x-component doesn't output anything at all, and just to confirm that yes it does work in a standard blade view.
Is this just a limitation of using a HTML HEREDOC or is there some way around this? The only thing I tried was adding a special global function called component that returns the component view like so:
function component(string $componentName, array $data = [], bool $render = true)
{
$view = view('components.'.$componentName, $data);
return $render ? $view->render() : $view;
}
And echoing that out within the HEREDOC, but then that kinda defeats the purpose of using the HEREDOC in the first place.
Any idea's or suggestions welcome, thank you!
From Laravel 9 you can now render a Blade template inline using Illuminate\Support\Facades\Blade::render($someString)
.
I don't have an example of your custom Blade component so I mocked one up:
@props([
'html',
'text'
])
<div>
<button>{{ $text }}</button>
</div>
Then to render this component via a string:
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Blade;
Route::get('/', function () {
$html = Blade::render(<<<HTML
<x-frontend.module-button href="#" text="This will not output anything" />
HTML);
return view('welcome', compact('html'));
});
Note: To get this to render correctly I had to disable the auto-escaping feature of Blade, so my welcome.blade.php
simply contained {!! $html !!}
.