We may include the same content in multiple pages, such as file headers, links to css or js, etc. We can use layout files to complete this function.
Let's create a new layout file, for example views/
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="/bootstrap/3.3.4/css/"> </head> <body> <div class="container"> @yield('content') </div> </body> </html>
We created an inexplicable structure and introduced bootstrap. Note that @yield is the layout placeholder for blade. In the future, our page content will be filled here and modified
@extends('layout') @section('content') <h1>About {{ $first }} {{ $last }}</h1> @stop
The above code means we use the layout file and then add content in the content segment.
Add in :
Route::get('about', 'PagesController@about'); Route::get('contact', 'PagesController@contact');
Add in :
public function contact() { return view(''); }
Create new view pages/
@extends('layout') @section('content') <h1>Contact Me!</h1> @stop
Check it out!
In the layout file, we can add multiple @yield , such as adding @yield('footer') in :
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="/bootstrap/3.3.4/css/"> </head> <body> <div class="container"> @yield('content') </div> @yield('footer') </body> </html>
For example, if there is a script in it, it can be placed in this paragraph.
@extends('layout') @section('content') <h1>Contact Me!</h1> @stop @section('footer') <script> alert('Contact from scritp') </script> @stop
There will be a dialog box to access contact, and about will still be displayed normally
Use @if to make judgments
@extends('layout') @section('content') @if ($first = 'Zhang') <h1>Hello, Zhang</h1> @else <h1>Hello, nobody</h1> @endif @stop
It can also be regarded as @unless is equivalent to if !, and @foreach, etc.
public function about() { $people = [ 'zhang san', 'li si', 'wang wu' ]; return view('', compact('people')); } @extends('layout') @section('content') <h1>Person:</h1> <ul> @foreach($people as $person) <li>{{ $person }}</li> @endforeach </ul> @stop
There is a situation where the data may come from a database and the collection may be empty, like this:
$people = [];
To handle this situation, please add @if to handle it
@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 all about this article. I hope it will be helpful to everyone to learn Laravel5.