Creating a view using Blade of laravel

PHP has many templating libraries available and Laravel’s Blade is one of the best. This recipe
will show an easily extendable way to get up-and-running with Blade templates, and quickly.

Getting ready

For this recipe, we need a standard Laravel installation.

How to do it…

To complete this recipe, follow these steps:
1. In the routes.php file, create new routes for our pages as follows:
Route::get(‘blade-home’, function()
return View::make(‘blade.home’);
Route::get(‘blade-second’, function()
return View::make(‘blade.second’);
2. In the views directory, create a new folder named layout.

3. In the views/layout directory, create a file named index.blade.php and add
the following code to it:
<!doctype html>
<html lang=”en”>
<meta charset=”utf-8″>
<title>My Site</title>
Welcome to
4. In the views directory, create a folder named blade.
5. In the views/blade directory, create a file named home.blade.php and add the
following code to it:
Our Blade Home
Go to {{ HTML::link(‘blade-second’,
‘the Second Page.’) }}
6. In the views/blade directory, create a file named second.blade.php, and add
the following code to it:
Our Second Blade Page

Go to {{ HTML::link(‘blade-home’, ‘the Home Page.’)
7. Test the views by going to http://{your-server}/blade-home (where yourserver
is our URL) and then clicking on the link, and viewing the source of the page
to see the Blade layout included.

How its Works..

To start, we create two simple routes that will return our Blade views. By using the dot notation,
we can see that we’ll be putting the files in the blade subdirectory of our views folder.
Our next step is to create a Blade layout view. This will be the skeleton of our pages and will
be put in the layout subdirectory of our views folder, and it must have blade.php as the file
extension. This view is simple HTML, with two exceptions: the @section() and @yield()
areas. This content is what will be replaced or added to in our views.
In our routes’ views, we begin the file by declaring which Blade layout to use, which for our
case is @extends(‘layout.index’). Then we can add and alter the content sections we
declared in our layout. For the page_title section, we want to display the text in the layout,
but we want to add in some extra text to the end. To accomplish that, we call @parent as the
first thing in that content area, and then put in any of our own content.
In @section(‘content’), there was no default text in the layout, so everything will be
added. Using Blade, we can also use the {{ }} braces to print out any PHP we need. In our
case, we’re using the HTML::link() of Laravel to display a link. Now, when we go to the
page, all the content area is put in the correct place in the layout.

Leave a Reply

Your email address will not be published. Required fields are marked *