[8.x] Add a BladeCompiler::renderComponent() method to render a component instance #40745
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR is similar to the functionality introduced in #40425.
This new method allows you to call
BladeCompiler::renderComponent($component)
, where$component
is an instance ofIlluminate\View\Component
, and get the HTML of the rendered component returned. Alternatively you may call therenderComponent
method from the Blade facade:Blade::renderComponent($component)
.Example
Rationale
Components are a great way to encapsulate parts of the view. Rendering a component programatically is useful if you want to render a component's HTML directly into a response. For example, if you wanted to dynamically update a component via XMLHttpRequest.
Currently to achieve this you would need to create a new view partial to return in the response, for the sole purpose of rendering the component:
The
Blade::render()
function makes this a bit easier, as you could render the component as a Blade string into the response, rather than needing to resort to a partial:However, this still doesn't have optimal ergonomics, especially with increasing numbers of properties. The
renderComponent
method cuts out the intermediate step and makes this simple:Note that if needed, attributes can be set on the component instance like so:
Implementation
The implementation is based on the
renderComponent
method of theIlluminate\View\Concerns\ManagesComponents
trait.