I have the following files:
foo.blade.php
<html>
<head>
</head>
<body>
<h1>Foo Template</h1>
@yield('content')
</body>
</html>
bar.blade.php
<h2>Bar Template</h2>
<div class="bar-content">
@yield('bar-content')
</div>
I want to create another file that is able to extend both the above templates. e.g something like this:
@extends('foo')
@section('content')
<p>Hello World</p>
@extends('bar')
@section('bar-content')
<p>This is in div.bar-content</p>
@endsection
@endsection
To give:
<html>
<head>
</head>
<body>
<h1>Foo Template</h1>
<p>Hello World</p>
<h2>Bar Template</h2>
<div class="bar-content">
<p>This is in div.bar-content</p>
</div>
</body>
</html>
How can I do this?
@extends lets you "extend" a template, which defines its own sections etc. A template that you can extend will define its own sections using @yield , which you can then put your own stuff into in your view file.
In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures while also remaining familiar to their PHP counterparts.
A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *. blade.
In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.
I would recommend using components. Here is an example.
It seems to me layout/include
has a weird logic when there are many of them and you start nesting them. Components are pretty straight forward. For these nested structures you are building there, components also have slots.
Use multiple files. for eg;
layout.blade.php:
@include('header')
@yield('layout_content')
@include('footer')
second.blade.php
@extends('layout')
@section('layout_content')
<div>
@yield('second_content')
</div>
@stop
third.blade.php
@extends('second.blade.php')
@section('second_content')
<h1>Hello World!</h1>
@stop
You can include @yield in any of the parent files and can be used in the child
I do not know if this will work, but try @include
instead of @extends
for your bar
template. The put your section for bar
below the other section (not nested). I did not tested this, so I hope it works ;)
// EDIT:
Try it with an if-statement in your foo
file:
<html>
<head>
</head>
<body>
<h1>Foo Template</h1>
@yield('content')
@if(isset($displayBar) && $displayBar == true)
@include('dashboard.test.bar')
@endif
</body>
</html>
And now the child view:
@extends('dashboard.test.foo')
@section('content')
<p>Hello World</p>
@endsection
<?php $displayBar = true ?>
@section('bar-content')
<p>This is in div.bar-content</p>
@endsection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With