Laravel Blade Templating

laravel blade

In the recent tutorials, we’ve gone from installing laravel all the way up to setting up RESTful Controllers. In the name of brevity, we’ve simply returned data to the screen when testing the routes, models, and controllers we have built. You may have been wondering about Views. Well we’re now ready to prettify things a little bit, and what better way than to incorporate Laravel’s Blade templating engine with Twitter Bootstrap to begin constructing our views. Le’ts do it!


Blade Templating Engine

Now we get to start making some views! You’ll remember that in our Blogposts Controller we were just returning the data to the browser like so:

<?php

class BlogpostsController extends BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		return Blogpost::all();
	}

Let’s start using Views instead! When we want to load a view, we’ll do so by using the make() method from the View Facade. We’ll also want to pass whatever data we need on over to the view and we can do it in one of three ways.

// using the with method
return View::make('blogposts/index')->with('blogposts', $blogposts);

//  using dynamic methods
return View::make('blogposts/index')->withBlogposts($blogposts);

//  passing in an array as 2nd argument to make
return View::make('blogposts/index', ['blogposts' => $blogposts]);

In the snippet above, blogposts/index is referring to /app/views/blogposts/index in your directory structure.


Master Pages

We’re going to start by creating a master page. The master page holds any repetitive html that we don’t want to have to recreate in all of the individual views. We’ll include jQuery and Twitter Bootstrap in this master page so we can have access to all of their great benefits. This file will reside in the /app/views/layouts directory.

<!doctype html>
<html>

<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<title>Larablog</title>
</head>

<body>
<div class="container">
  <div>
    <h1>{{ link_to('/', 'Larablog') }}</h1>
    <p class="lead">Laravel, Blade, and Bootstrap working in harmony.</p>
  </div>
  <div class="row">
    <div class="col-sm-8 blog-main"> @yield('content') </div>
  </div>
</div>
</body>

</html>

Cool! In the snippet above you’ll notice two things that may look a little peculiar.

{{ link_to('/', 'Larablog') }}
The {{ and }} indicate sections that will get echoed out to the screen. This line also makes use of the link_to function so that we can create a home link so to speak on our blog page that links to the root. The link_to function takes two arguments, the path you’ll link to, and the anchor text.

@yield('content')
The @yield keyword is a way to do code substitution or short codes so to speak. We’ll define what we are actually going to put in this yielded area in our view files.


Creating View Files

For this example we need a few view files. In our /app/views/blogposts directory we can create index.blade.php as well as show.blade.php. Those files will look something like this:

index.blade.php

@extends('layouts.default')

@section('content')
  @foreach ($blogposts as $blogpost)
      
  • {{ link_to("/blogposts/{$blogpost->slug}", $blogpost->title) }}
  • @endforeach @stop

    show.blade.php

    @extends('layouts.default')
    
    
    @section('title')
    	{{ $blogpost->title }} 
    @stop
    
    
    @section('content')
      

    {{ $blogpost->title }}

    {{ $blogpost->body }}

    @stop

    This might be a little new to you, it was to me. In fact I would say there are a lot of pros and cons to using a templating engine, but since we’re really trying to be Laravel Purists here, we’ll put in the extra effort and dig in to Blade. The view files need to begin with the @extends keyword like you see here in order to reference the master page to use. In addition, you define areas of code to inject into the master page by defining sections using the @section and @stop keywords. All of the normal programming constructs, and some new ones, are available to you as you see here.

    If Statements

    @if (count($blogposts) === 1)
        I have one blogpost!
    @elseif (count($blogposts) > 1)
        I have several blogposts!
    @else
        I don't have any blogposts!
    @endif
    
    @unless (Auth::check())
        You are not signed in.
    @endunless

    Loops

    @for ($i = 0; $i < 10; $i++)
        The current value is {{ $i }}
    @endfor
    
    @foreach ($blogposts as $blogpost)
        

    This is blogpost {{ $blogpost->title }}

    @endforeach @while (true)

    I'll keep looping!

    @endwhile

    Includes

    @include('view.name')

    Update The Blogposts Controller

    Now that we have a master page and some view files created, we can modify the Blogposts Controller so that it will make use of views instead of just returning data to the browser. Here are the modifications to be made to the index() and show() methods:

    <?php
    
    class BlogpostsController extends BaseController {
    
    	/**
    	 * Display a listing of the resource.
    	 *
    	 * @return Response
    	 */
    	public function index()
    	{
    		$blogposts = Blogpost::all();
    		return View::make('blogposts/index')->withBlogposts($blogposts);
    	}
    
    	/**
    	 * Show the form for creating a new resource.
    	 *
    	 * @return Response
    	 */
    	public function create()
    	{
    		//
    	}
    
    	/**
    	 * Store a newly created resource in storage.
    	 *
    	 * @return Response
    	 */
    	public function store()
    	{
    		//
    	}
    
    	/**
    	 * Display the specified resource.
    	 *
    	 * @param  int  $id
    	 * @return Response
    	 */
    	public function show($id)
    	{
    		 if (is_numeric($id))
    		 {
    			 $blogpost = Blogpost::find($id);
    			 return View::make('blogposts/show')->withBlogpost($blogpost);
    		 }
    		 else
    		 {
    			 $column = 'slug'; // This is the name of the column you wish to search
    		
    			 $blogpost = Blogpost::where($column , '=', $id)->first(); //  find the name to id association
    			 return View::make('blogposts/show')->withBlogpost($blogpost);
    		 } 
    	}
    
    	/**
    	 * Show the form for editing the specified resource.
    	 *
    	 * @param  int  $id
    	 * @return Response
    	 */
    	public function edit($id)
    	{
    		//
    	}
    
    	/**
    	 * Update the specified resource in storage.
    	 *
    	 * @param  int  $id
    	 * @return Response
    	 */
    	public function update($id)
    	{
    		//
    	}
    
    	/**
    	 * Remove the specified resource from storage.
    	 *
    	 * @param  int  $id
    	 * @return Response
    	 */
    	public function destroy($id)
    	{
    		//
    	}
    
    }
    

    Review The Program Flow

    Let’s review the flow of the program before we actually try to load it up in our browser.

    We have a routes.php file that has registered all of our restful routes for us.
    Route::resource('blogposts', 'BlogpostsController');

    We’ll then hit a controller which has the logic for our index() and show() methods. See code above.
    class BlogpostsController extends BaseController {

    The controller will make use of the Blogpost model.

    class Blogpost extends Eloquent {
    	protected $guarded = array();
    
    	public function tags() 
    	{
    		return $this->belongsToMany('Tag');	
    	}
    }
    

    By making use of the model, we can fetch whatever data we want from the database. Once the controller has used the model to fetch the data from the database, it will go ahead and render a view using View::make() passing along any required data. When the controller instructs to make the view, Laravel will intelligently make use of the master page in addition to the snippets of html found in the view files to create the final rendered page.


    Let’s Try It Out!

    We set up a lot of things in our route, controller, model and view. Let’s test it out to see what we get 🙂

    First up we’ll visit http://you.rock/blogposts
    laravel blog list posts

    Heeyyyy 🙂 Looking good Charlie Brown!

    Now that we see a listing of all the blogposts, go ahead and click one of the links to drill down and see specific information about the blogpost. We’ll try http://you.rock/blogposts/laravel-eloquent-orm-tutorial
    laravel blog single post

    Great! Viewing individual posts using a pretty URL syntax works too!

    Another bonus is that by including Twitter Bootstrap in the master page, we can see the visual looks a whole lot better than when we were first just dumping JSON to the browser. When we just want to test out our logic and not worry about the front end, it is still great to be able to simply return JSON or use the dd(), or die dump function.

    This is really exciting, we’re making a ton of progress in getting our skills up to speed using Laravel!