Laravel | Blade Templates Inheritance
A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *.blade.php. In Laravel, most of the times frontend files are stored in resources/views directory. Blade files support PHP and are compiled into plain PHP and cached in the server so that we don’t have to do the extra work of compiling the templates again when a user access a page again, thus using Blade is as efficient as using PHP files itself in the frontend.
Template Inheritance: In most of the modern webpages, a fixed theme is followed in all the webpages. Thus it is greatly effective to be able to reuse your code so that you don’t have to write again the repeating parts in your code and Blade greatly helps you in achieving this.
- Defining a layout: Let’s do that with an example and create a file called layout.blade.php in resources/views directory as shown below:
Now, in the code given above, we use @yield directive to tell the Blade that we are going to further extend this part in the child blade pages. Further, notice that each of yield directive is having a name like title for first one and content for second one. These names are going to be used later in the child page to tell that this section is extended here.
- Extending a layout: Let’s do that too now and create a page at resources/views directory called mypage.blade.php as given below:
<h1>My first page with Blade Inheritance.</h1>
In this code, we are first using the @extends directive which tells which blade page we are inheriting this page from. In our case, it is going to be layout as we are going to inherit this page from layout.blade.php, we created earlier. Further, we use the @section directive to extend each of the @yield directive’s of the parent blade file. We have to tell the name of each @yield directive we are extending here in the @section directive as we have done in code above. Make sure after writing the code you end the directive with @endsection. All the @yield sections will be replaced with the respective code in the child blade pages. One last thing left to make this work is adding a route as given below in your routes/web.php.
We just created a route to /mypage and in the callback function we are serving mypage.blade.php. Notice that Blade automatically looks for files in resources/views directory.
In the output you can see how @yield(‘title’) is replaced with Child Page and @yield(‘content’) is replaced with My first page with Blade Inheritance.