To create and use Blade layout templates for consistent page structure in Laravel, follow these steps:
Create a new layout template file: In the resources/views/layouts
directory, create a new Blade template file, e.g., app.blade.php
. This file will serve as the base layout for all your pages.
Define the basic structure in the layout template: In the app.blade.php
file, define the basic HTML structure for your pages, including the <html>
, <head>
, and <body>
tags. You can also add a navigation bar or any other common elements that will appear on all pages.
Define the sections in the layout template: Within the <body>
tags, define sections using the @yield
directive. For example, you can define a content
section where the content of each specific page will be injected. You can also define optional sections for specific page elements that might change across pages, such as a sidebar or footer.
<body>
{{-- Navigation bar --}}
<div class="content">
@yield('content') {{--section to inject content of each specific page--}}
</div>
{{-- Optional page element sections --}}
{{-- Footer --}}
</body>
Create a new page template: Create a new Blade template file for each page in the resources/views
directory. For example, create a welcome.blade.php
file for your home page.
Extend the layout template in the page template: In each page template, use the @extends
directive to extend the layout template. Specify the name of the layout template file (without the .blade.php
extension). For example:
@extends('layouts.app')
@section
directive to define the content that will replace the @yield('content')
section in the layout template. For example:@section('content')
<h1>Welcome to My Website</h1>
<p>This is the home page.</p>
@endsection
@include
directive.Now, when you visit the URL corresponding to each page, Laravel will use the specified layout template and inject the content from the respective page template into the @yield('content')
section. This provides consistent page structure across your Laravel application.