skip to Main Content

In React, I can use fragments (<>…</>) to group multiple elements without adding extra nodes to the DOM:

<>
    <div>First element</div>
    <div>Second element</div>
</>

Is there a similar concept in Laravel Blade? I want to avoid using an empty div when creating some components

2

Answers


  1. Yes, Laravel Blade has a similar concept to React fragments. In Blade, you can use the @fragment directive, which works similarly to fragments in React. This allows you to group multiple elements without adding extra DOM nodes.

    In Laravel 8.0 and later versions, you can use the @fragment directive like this:

    @fragment
        <div>First element</div>
        <div>Second element</div>
    @endfragment
    

    This is very similar to using fragments in React and doesn’t require you to add an extra wrapper div.

    Login or Signup to reply.
  2. Yes, Laravel Blade has a feature similar to React’s fragments

    Option 1:
    You can also use the @once directive to prevent unnecessary wrapping and ensure the content is only rendered once. This is useful when dealing with elements like inline scripts or components that should be rendered conditionally.

    @once
        <div>First element</div>
        <div>Second element</div>
    @endonce
    

    Option 2:
    You can directly include Blade partials without adding extra wrapper elements using the @include directive.

    Create a Blade partial view:

    <!-- resources/views/partials/elements.blade.php -->
    <div>First element</div>
    <div>Second element</div>
    

    Include it in your main Blade template:

    @include('partials.elements')
    

    This will include the content without adding any unnecessary wrapper elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search