To extend a Blade layout template with a child view in Laravel, you can follow these steps:
Create a Blade layout template file:
Create a new Blade template file, for example layouts/app.blade.php
. This will be the parent layout file that will be extended by child views.
<!-- layouts/app.blade.php -->
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
<header>
<!-- header content -->
</header>
<div class="content">
@yield('content')
</div>
<footer>
<!-- footer content -->
</footer>
</body>
</html>
Create a child view:
Create a new Blade template file, for example home.blade.php
. This will be the child view that extends the parent layout file.
<!-- home.blade.php -->
@extends('layouts.app')
@section('title', 'Home')
@section('content')
<!-- content for the home page -->
@endsection
Render the child view: In your controller or route, return the child view in the response.
// HomeController.php
public function index()
{
return view('home');
}
The view()
function returns an instance of the View
class, which will render the child view and automatically inherit the layout defined in the @extends
directive.
Customize and add content to the parent layout:
In the parent layout file, you can customize and add content that will be displayed across all child views. Any content placed within the @yield
directive will be replaced with the content from the child view.
<!-- layouts/app.blade.php -->
<!-- ... -->
<header>
<!-- header content for all views -->
</header>
<!-- ... -->
With these steps, you can extend a Blade layout template with a child view in Laravel. The child view can provide specific content to be displayed within the parent layout, allowing for code reusability and maintaining a consistent design across multiple views.