In multiple pages we may include the same content, such as file headers, linked css or js, etc. We can use layout files to accomplish this function.
Let’s create a new layout file, such as views/layout.blade.php
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css"> </head> <body> <div class="container"> @yield('content') </div> </body> </html>
We created an incomprehensible structure and introduced bootstrap. Note that @yield is the layout placeholder of blade. Our page content will be filled here in the future. Modify about.blade.php
@extends('layout') @section('content') <h1>About {{ $first }} {{ $last }}</h1> @stop
The above code means that we use the layout file layout.blade.php, and then add content in the content section.
Add in routes.php:
Route::get('about', 'PagesController@about'); Route::get('contact', 'PagesController@contact');
In PagesController.php add:
public function contact() { return view('pages.contact'); }
New view pages/contact.blade.php
@extends('layout') @section('content') <h1>Contact Me!</h1> @stop
Check it out!
We can add multiple @yields in the layout file, such as adding @yield('footer') in layout.blade.php:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css"> </head> <body> <div class="container"> @yield('content') </div> @yield('footer') </body> </html>
For example, if there is a script in contact.blade.php, it can be placed in this section.
@extends('layout') @section('content') <h1>Contact Me!</h1> @stop @section('footer') <script> alert('Contact from scritp') </script> @stop
There will be a dialog box when accessing contact, but about is still displayed normally
Use @if for judgment
@extends('layout') @section('content') @if ($first = 'Zhang') <h1>Hello, Zhang</h1> @else <h1>Hello, nobody</h1> @endif @stop
Can also be regarded as @unless equivalent to if !, and @foreach, etc.
public function about() { $people = [ 'zhang san', 'li si', 'wang wu' ]; return view('pages.about', compact('people')); } @extends('layout') @section('content') <h1>Person:</h1> <ul> @foreach($people as $person) <li>{{ $person }}</li> @endforeach </ul> @stop
In one case, the data may come from the database and the collection may be empty, like this:
Copy code The code is as follows:
$people = [];
To handle this situation, please add @if handler
@extends('layout') @section('content') @if (count($people)) <h1>Person:</h1> <ul> @foreach($people as $person) <li>{{ $person }}</li> @endforeach </ul> @endif <h2>Other info</h2> @stop
That's better.
The above is the entire content of this article. I hope it will be helpful to everyone learning Laravel5.