Is it possible to pass and render HTML tags between Livewire components?
For example, if I have a parent component that renders a nested hero component, is it possible to pass a variable like $hero_text
from the parent that might include and render a <br>
tag or something?
Like the equivalent of using the <<<'HTML'
notation from within the class files that are created for livewire component.
This doesn’t work, but an example of what I’m thinking of would be:
@livewire('components.hero', [
'img' => '/img/index/hero-wide.jpg',
'hero_text' =>
return <<<'HTML'
<h1 class="text-3xl">This is header text</h1>
<p class="text-sm">This is subheader text</h1>
HTML;
])
The above would obviously just break, and passing something like:
'hero_text' => 'This is upper text <br> This is lower text'
would print the <br>
as text and not render the HTML.
The use case would be for a hero that can have a variety of different text configurations within it without having to create three or four different $hero_text_1
, $hero_text_2
parameters that render based on if statements.
Or is there a better way to do this?
Thanks!
2
Answers
You can pass HTML content from a parent to a child Livewire component and render it using the
@html
directive. This allows for flexible content rendering without the need to split the content into multiple variables and conditionally render them.In your parent component, you pass the HTML string as a parameter to the child component:
And in your child component (for example, components.hero), you would render the hero_text like so:
!!!!!! NOTE
Always ensure the HTML content is sanitized, especially if it includes user-generated content, to prevent security vulnerabilities like XSS.
The request is a bit strange and it will be useful to see a sample of the child component.
Also I don’t understand why you use return to pass the HTML data to the child component (I suppose it’s a typo).
Anyway the answer is simple: with blade you can echo unescaped data using the
{!! $text !!}
notation instead of the usual{{ $text }}
notation: