Laravel Blade Once Component
Published on by Eric L. Barnes
As of Laravel 7.25, Blade now includes a new @once
component that will only render the items within the tags one time. It’s a little hard to explain and much easier to show with an example, and here is one Taylor included in the original pull request:
Component content here... @once <script> This will only be included in the template once even if component is rendered multiple times. </script>@endonce
Then Mohamed Said followed up with another example:
@once<template id="recieptsTemplate"> <div class="flex flex-column items-center"> <div class="w-1/2" data-reciept="paid_at"></div> <div class="w-1/4" data-reciept="amount"></div> </div></template>@endonce <div data-id="receipts" class="divide-y divide-grey-300"></div>
This component renders a list of receipts. The template for the receipt has to be rendered once in the entire page while the component itself can be used multiple times.
This once
feature is now pulled into Laravel starting with v7.25 so you can start using it today.
Eric is the creator of Laravel News and has been covering Laravel since 2012.