image alt

Blade Layouts Two Ways

blog image

There are two ways of making the blade templates reusable.

i) Blade Layouts
ii) Blade Components

These files contain full HTML structure from the <!DOCTYPE html> tag to <html>, to <head>, and to <body> tag, the full HTML structure. This approach is bad because it poses duplication in files and if you need to add a change like including a new CSS file, you will have to change all files to add that change. There are two ways to mitigate this problem in Laravel.

i) Blade Layouts:

Split your view template files in the following two parts:

a) The wrapping part

Create a new file in your resources/views directory and name it layout.blade.php. You can name it anything but lets have it like this for now. Now take out the wrapping part of your templates (the doctype tag, the opening/closing tags of htmlhead, and body.) and put in layout.blade.php. In between the body tags, place this Blade directive @yield('content'). This is the place where your template-specific code will be yielded. The word content in the directive is basically a key. You need to use this key in the templates to extend this layout.

b) And the view-specific part

The loop part for posts.blade.php listing blog posts, and the article part for the post.blade.php. In the start of these templates, you put the directive @extends('layout') which means this template file is using the layout.blade.php file for the wrapping portion of HTML. Then you place your template-specific code in the block @section('content') ... @endsection. Here the word content in the section directive is the key we used in the @yield('content') directive in our layout.blade.php.

ii) Blade Components:

You can think of a Blade Component as a way to wrap a piece of HTML. You create Blade Components by creating a directory component in your resources/views folder. Whatever blade file you add to this directory is instantly available as a Blade Component.

Move your layout.blade.php file to the Components folder so that it is available as a Blade Component. You refer to a Blade Component by prefixing its file name with x- like . In layout.blade.php replace the Blade directive @yield() with the Blade Component {{ $slot }}. Here $slot is a special variable that acts as a default slot for your component.

In your template files posts.blade.php and post.blade.php, remove the Blade directives @extend and @section and wrap your code in the component directives  and .

More Info : Blade Templates | laravel (devdocs-fr.github.io)

 

 

Thanks for reading ❤

Ready to grow your business digitally?