Using named views and view composers
This recipe will show how to use Laravel's named views and view composers to simplify some of our routes' code.
Getting ready
For this recipe, we'll be using the code created in the Creating menus in Laravel recipe. We'll also need the assets
package installed in the Adding assets recipe.
How to do it...
To complete this recipe, follow these steps:
In the
routes.php
file, add a file namedview
, and add the following code to it:View::name('menu-layout', 'layout');
In
routes.php
, add a view composer as follows:View::composer('menu-layout', function($view) { Asset::add('bootstrap-css', 'http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css'); $view->nest('menu', 'menu-menu'); $view->with('page_title', 'View Composer Title'); });
In
routes.php
, update the menu routes as follows:Route::get('menu-one', function() { return View::of('layout')->nest('content', 'menu-one'); }); Route::get('menu-two', function() { ...