How to auto-load Blade layouts

blade template

Last weekend my mate Dave Shoreman figure it out how to use the Blade template engine from Laravel outside the framework. For me that was awesome and I started using it with CodeIgniter right away. After a few tests and seeing that everything was working it was time to start tweaking things.

I never used any template library before Blade. I just didn’t like any. So I always use Jamie Rumbelow’s way of using views with his MY_Controller.php configuration. 

This configuration is strongly driven by the ideals of convention over configuration, favoring simplicity and consistency over configuration and complexity.

Assume you have a controller called products with the following methods: index, by_category, detail.

Using Jamie’s way you are going to end up with a view folder like this:

VIEWS
  →products
    →index.php
    →by_category.php
    →detail.php
  →layouts
    →application.php

I actually like this structure. This way you always have to follow a pattern and it’s way easier to know where is everything.

Also not having to load views in every controller method is great:

$this->load->view('foo');

When I started using Blade I wanted to follow the same structure using blade layouts. Also I didn’t want to manually echo the blade views. 

I wrote something based on Jamie’s code.

Using this you don’t have to define a layout in your MY_Controller since with blade you can extend your blade files to layouts.

If by any chance you have a method that you don’t want to auto-load any blade files, and you want to load them yourself instead, you can do it.

Pretty cool right?