Using non-Blade views in Blade layouts
As of late I have been using Laravel a lot to build my applications. I recently ran into the issue of needing to embed a non-Blade view into a Blade layout. The reason for this was that I was using Ember.js, which uses Handlebars.js templates. Handlebars.js templates, much like Laravel’s Blade templates, use {{ and }}. Including Handlebars.js templates in a Blade template did not make Laravel happy. My solution was to create a regular view file that contained my JavaScript templates. The issue I ran into was getting the view embedded into my layout.
Most of my Blade templates looked something like this:
@layout('layouts.common')
@section('content')
<!-- ... -->
@endsection
Breaking this down, it does two things. It declares that we are using the layouts.common layout and embeds the content section into the layout. How can we do this without using a Blade template?
The documentation explains how to specify a layout using the layout property of a controller:
class Ember_Controller extends Base_Controller {
public $layout = 'layouts.common';
}
Embedding the view into the layout isn’t as obvious. Digging through the API, I discovered the \Laravel\Section::inject() method which lets you inject inline content into a section. Using this I was able to inject the contents of my view into the content section (@yield('content')) of my layout.
class Ember_Controller extends Base_Controller {
public $layout = 'layouts.common';
public function action_index()
{
Section::inject('content', View::make('ember.index'));
}
}
As a side note, Laravel is an awesome framework with some great documentation. But if you look a little deeper and check out the API, there are some really useful methods that aren’t documented.