How to use Blade in CodeIgniter (and just about any PHP (un)framework you can think of)

Update (14/04/2013): While this worked awesomely when I wrote it in December, that was a long LONG time ago in Internet years. Blade has since moved to another repo and the codebase has changed dramatically, so the details on this page no longer work. I also have a day job taking up all of my time currently, so I have no time left to figure out a new hack. If you DO have time, feel free to play around - bits of this post could still be useful to you.


I was on IRC last night when Marco Monteiro sent me a PM saying he had a problem getting Composer to work in CodeIgniter. In the end it turned out he was trying to throw use Namespace\Bla lines somewhere in the middle of the Controller, which was never going to work.

Anyway, we got talking more about Composer, and he pasted a link to Blade on Packagist saying how badly he wanted it in CI. Long story short (ish), I randomly decided to try it out and see what happened. I have no idea why, but it seemed like a good idea at the time.

Installation

Before you do anything you'll need to install Composer to your CodeIgniter project. I won't go into that in this post, but there are already some great guides out there. Two that come to mind are Phil Sturgeon's tutorial on net tuts+, and Marco's Starting with Composer post.

Once you've got that sorted, open your composer.json file and add these two lines:

{
	"require": {
		"illuminate/blade": "dev-master",
		"illuminate/filesystem": "dev-master"
	}
}
By default Composer will fetch the latest release, but those are a couple months old so we need to force it to download the current commit from the master branch. To do that we set the version to 'dev-master'.

Now simply run composer update (assuming you moved or linked your composer.phar to /usr/bin/composer) and that's about it for the installation. Well, apart from the config. Create a new file blade.php in your application/config directory with this code:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['views_path'] = APPPATH . 'views/blade/';
$config['cache_path'] = APPPATH . 'cache/blade/';

Tweaking Things a Little

There are currently a couple minor issues in the Blade Compiler which you might want to fix*. Bear in mind that Composer will complain about uncommitted changes if you try to update after modifying the files manually.

// This updated method fixes block comments with a newline
// char immediately after the opening {{-- tag.
protected function compileComments($value)
{
	$value = preg_replace('/\{\{--(.*?)--\}\}/', "", $value);

	return preg_replace('/\{\{--(\n?)(.*?)--\}\}/s', "$1", $value);
}

Loading Blade...

I wanted to keep in line with CI's loading syntax so that using Blade in CI will come naturally to anyone that knows their way around a CodeIgniter project. As such, create a new file in your application/core directory called MY_Loader.php and paste in the content of this GitHub Gist:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require 'vendor/autoload.php';
use Illuminate\Blade\Environment;
use Illuminate\Blade\Loader;
use Illuminate\Blade\View;

class MY_Loader extends CI_Loader {

	public function __construct()
	{
		parent::__construct();
	}

	public function blade($view, array $parameters = array())
	{
		$CI =& get_instance();
		$CI->config->load('blade', true);

		return new View(
			new Environment(Loader::make(
				$CI->config->item('views_path', 'blade'),
				$CI->config->item('cache_path', 'blade')
			)),
			$view, $parameters
		);
	}
}
Save that file and you're ready to start loading Blade views!

...and some Views

In your controller, load a view as normal but replacing view with blade. You can pass data to the view in one of several ways:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

	public function index()
	{
		// Prepare some test data for our views
		$array = explode('-', date('d-m-Y'));
		list($d, $m, $y) = $array;

		// Basic view with no data
		echo $this->load->blade('home.index');

		// Passing a single value
		echo $this->load->blade('home.index')->with('day', $d);

		// Multiple values with method chaining
		echo $this->load->blade('home.index')
			 ->with('day', $d)
			 ->with('month', $m)
			 ->with('year', $y);

		// Passing an array
		echo $this->load->blade('home.index', array(
			'day' => $d,
			'month' => $m,
			'year' => $y
		));
	}
}

If you need to load views ready for later, you can do that too:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {

	public function index()
	{
		// Load the view into a variable
		$view = $this->load->blade('home.index');

		// Attach some data
		$view->with('time', date('H:i:s'));

		// Render the parsed view
		echo $view->get();
	}
}

Usage Info / Gotchas

There are a couple things to bear in mind when using Blade in CI...

  • ->render() is now ->get()
  • @layout is now @extends
  • @endsectionis now @stop
  • Missing some compilers like @forelse*
  • Don't forget to end views with .blade.php
  • maybe some others I've missed...

If you've got this far then hopefully everything worked out well and your CodeIgniter project is successfully parsing Blade views. If anything went wrong or you spot something I've missed, post a comment and I'll (try to) get it fixed. Over time the code in this post will indubitably** break as the supporting repositories get updated, but the joy of Git is you can always go back in time if needed. For reference, the latest commits right nowas I post this are 2e5a42d and 763c1ce for the filesystem and blade repositories respectively.

Usage outside of CodeIgniter is essentially the same. All you should need is the statement returned from MY_Loader->blade(). Here's a bare-minimum example:

<?php

require 'vendor/autoload.php';
use Illuminate\Blade\Environment;
use Illuminate\Blade\Loader;
use Illuminate\Blade\View;

function blade($view, array $parameters = array())
{
	return new View(
		new Environment(Loader::make(
			'path/to/blade/views',
			'path/to/blade/cache'
		)),
		$view, $parameters
	);
}

echo blade('home.index')->with('name', 'Dave');

*tobsn created a pull request on the main Laravel repo that fixes a lot of issues. Feel free to merge some changes in from there, but pay close attention as class and method names differ between laravel/laravel and illuminate/blade.

** Thanks to David Wosnitza for the new word of the day! Well, every day's a school day as my old boss would say.

  • http://twitter.com/marcogmonteiro Marco Monteiro (@marcogmonteiro)

    I love you so much :p

  • http://twitter.com/rei_liit John Kevin Basco (@rei_liit)

    are there any issues or disadvantages in using Blade inside CodeIgniter?

    • codeM0nK3Y

      Apart from (maybe) the issues mentioned in the article, there are no disadvantages/issues as far as I’m aware, compared to using it inside Laravel or any other framework. With that said, I do need to update the post at some point as the blade repo no longer exists since Laravel 4 changed to use a driver-based system for template systems, much like Laravel 3 already uses for database manipulation.

      Ok, I guess there is one disadvantage: Blade as a composer package is still in alpha, along with the rest of Laravel 4. That means it can change at any time, which can potentially break your application if you update it blindly.

      If you fancy experimenting, Blade now lives inside the illuminate/view repository.

  • Lee

    Any idea on how to tweak this to work with the new Illuminate/view repo, i have gotten so far but ran into “Class Illuminate\View\Loader not found” and I’m unsure what to replace loader with?

  • John Smith

    any update please the this is not working

    may be issue is Blade now lives inside the illuminate/view repository.

    how to solve it.

    • codeM0nK3Y

      While that is part of the issue, it is trivial and far from the only one.

      There have been a lot of changes to blade since I wrote this post, so it is more difficult to get it working. If you want to have a go, let us all know how you get on! Unfortunately though I have a day job taking up all my time; until my job requires it I can’t spend any time on this yet even if I want to.

  • http://gravatar.com/williamak William Knauss

    I recently worked on this, check out my project: https://github.com/williamknauss/laravel4-views-in-codeigniter