Change language

Laravel | Blade pattern inheritance

Template inheritance.In most modern web pages, all web pages use a fixed theme. Thus, it is very efficient to be able to reuse your code so that you don’t have to write repetitive parts in your code again, and Blade will help you a lot with that.
  • Layout definition: let’s do it with an example and create a file called layout.blade.phpin the directoryresources / views,as shown below: "en" > < title > @yield ( ’title’ ) < / title > < / head >

    < / html >
    Now in the above code we use the @ directive yield,to tell Blade that we’re going to extend this part to the Blade child pages. Also, note that each of the yield directives has a name like headingfor the first and contentfor the second. These names will be used later in the child page to say that this section is expanded here.
  • Extending the layout:let’s do it now and create a page in the resources / viewstitled mypage.blade.php, as shown below: @ extends ( ’layout’ ) @ section ( ’title’ ) Child Page @ endsection @ section ( ’content’ )

    My first page with Blade Inheritance. < / h1 > @ endsection In this code, we first use the @extends directive,which tells which blade page we inherit this page from. In our case, this will be the layout, since we are going to inherit this page from the layout.blade.phpthat we created earlier. Next, we use the @sectiondirective to extend each of the @yielddirectives of the parent server blade . We must specify the name of each @yield directive thatwe expand here in the @section,directive as we did in the code above. Make sure you end the @endsection directive after writing the code. All @yieldsections will be replaced with the corresponding code on the child bladespages. The last thing left to do for this job is - add the route given below in your route / web.php . Route::get ( ’/ mypage’ , function () { return view ( ’mypage’ ); }); We’ve just created a route to / mypage and in the callback function we are serving mypage.blade.php. Note that Blade automatically searches for files in the resources / views directory.

  • Output:
  • In the output you can see how @yield (’ title ’)is replaced by childpage,and @yield (’ content ’)replaced by My first page with Blade Inheritance.
SO 1 data error