Posted in Laravel

Add multiple contents to @yield from @section

Sometimes, we may extend/include more than one template inside a layout. When we need to define a section of content in a single yield, it perfectly does its job. But when there is a situation that needs to include multiple sections inside a single yield, the first section is overridden by the next section resulting in displaying only the last section in the yield directive.

Say,

views\layouts\template.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
@yield('content')
...
...
...
@yield('scripts')
</body>
</html>

When page.blade.php has:

@extends('layouts.template')

@section('content')
...
@include('partials.content')
...
@endsection


@section('scripts')

    alert('page');

@endsection

content.blade.php has:

@section('scripts')

    alert('content');

@endsection

When the code is executed, it can be seen that only content gets alerted and not the page. To overcome this, we have to use @stack provided by Laravel that stacks the contents:

views\layouts\template.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
@yield('content')
...
...
...
@stack('scripts')
</body>
</html>

When page.blade.php has:

@extends('layouts.template')

@section('content')
...
@include('partials.content')
...
@endsection


@push('scripts')

    alert('page');

@endpush

content.blade.php has:

@push('scripts')

    alert('content');

@endpush

Now, when executed, we could see both page and content gets alerted

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s