nabeel shahzad

Breadcrumbs for your Cake (2.1 feature)

without comments

CakePHP 2.1+ (currently in beta) comes with an awesome new feature called view blocks and view extensions (official docs here). This allows you to modify views, append to them, and change them, based on the content that might come later on in your code.

Previously, for building a breadcrumb, there was a giant if/else tree for parsing the request object, and views and helpers all structured to allow for the flexibility. In short, a nightmare. Now with view blocks functionality, it reduces it down to a very simple set of elements, which can be called in meaningful views.

View blocks are built as, you guessed it, blocks. Each block has a name (you chose it, whatever is relevant, “sidebar”, “breadcrumb”). You define a block as such:

Where do you place this? In a view file. For example, when a user goes to mysite.com/listings/add, it loads a view in Listings/add.ctp. Inside this file, at the top, you do can do:

This says that when this view (Listings/add.ctp) is loaded, then the breadcrumb should be “Home > Add Listing”. Of course this is simplified (I removed any HTML, etc, just to demonstrate).

Now that we have one view block, we need to pull this into the main layout. Since the breadcrumb shows up before any content, we will structure it using an element, which is pulled into the default layout file. I have an element, in Elements/breadcrumbs/base.ctp, which houses the basic structure of my breadcrumb. This element is called from my Layouts/default.ctp (also, super simplified):

The $this->fetch(‘breadcrumb’) is getting a block by the name of breadcrumb. I check to see if that block exists; if it doesn’t, then I output a default item of “Home”. Otherwise, I output the contents of the “breadcrumb” block.

Then when you load the page, it will show Home, and if you go to Listings/add, it will show Home > Add. Pretty simple! In my views, instead of calling the start()/end(), I have an element, under Elements/breadcrumbs/single.ctp, that builds a single level breadcrumb:

You can clean this up even more by automating it from the $this->request, and using $title_for_layout. I also have another view, which takes an array as a parameter, to build multi-level breadcrumbs:

Hope this helps! The $scripts_for_layout has also been deprecated in favor of of the view-blocks feature, which create, since now Javascript file can be included on a page-by-page basis, using $this->append

Be Sociable, Share!

Written by Nabeel

January 31st, 2012 at 2:24 pm

Posted in CakePHP,php