Manage Layout In Laravel
There are some directives in laravel @section, @yield, @stack and @push, these are basically used to manage layout. The @section directive, as the name implies, defines a section of content. The @yield shows the content of the given section. The @stack & @push directives, blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. An example is given below to understand laravel layout clearly.
Step 1 :
Make a folder in resources/view and make four files named script.blade.php, stylesheet.blade.php, menu.blade.php and master.blade.php. Then copy all the scripts link to the script.blade.php and all CSS files link to the stylesheet.blade.php and add only the HTML of menu section to the menu.blade.php.
Step 2 :
Open stylesheet.blade.php and script.blade.php and add the directives “@stack(‘css’)” and “@stack(‘script’)” respectively to the file at end of the file. If we need to add new CSS file or javascript file then we just use following code in that page.
//For pushing css file @push('css') <link rel="stylesheet" href="{{ URL::asset('public/css/icon-font.min.css') }}" type='text/css' /> @endpush
And
//For pushing js file @push('script') <link rel="stylesheet" href="{{ URL::asset('public/css/icon-font.min.css') }}" type='text/css' /> @endpush
This file will be placed to stylesheet.blade.php or script.blade.php file automatically.
Step 3 :
In the master.blade.php file, add the following code
<!DOCTYPE HTML> <html> <head> <title>Manage Laravel Layout</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Manage Laravel Layout" /> @include('user.layout.stylesheet') </head> <body> <div class="page-container"> @yield('body') <!-- footer --> <div class="copyrights"> <p>© 2017 Datainflow. All Rights Reserved.</p> </div> <!-- end footer --> </div> @extends('user.layout.sidebarMenu') @extends('user.layout.script') </body> </html>
@yield(‘body’) is used for place the content here from my page, which is in the step 4.
Step 4:
Resources/views/index.blade.php, in this file all the css, scripts and html will be combined here.
@extends('user.layout.master') @push('css') <link rel="stylesheet" href="{{ URL::asset('public/css/icon-font.min.css') }}" type='text/css' /> @endpush @section('body') <h1>testing laravel layout</h1> @endsection
Here we extends master.blade.php file, in the master. blade.php, all css and scripts are included.
Here we use @section(‘body’), and the <h1> tag content will place to the @yield(‘body’). in the @push section, the stylesheet will be placed to the stylesheet.blade.php file at the position of @stack(‘css’).