Monday, January 11, 2010

Zend Framework Route Context Plugin

See Zend Framework Route Context Plugin at its new home on

I want to share a simple, yet very useful, custom Zend Framework plugin that we use on almost all of our projects. The plugin (and associated code in the layout file) provides the Zend Framework route context as CSS classes on the body element. This allows us to change the design (using CSS) and/or behavior (using unobtrusive JavaScript) on the page based on the Zend Framework route. For example if the module name was default, the controller name was news, and the action was get then the opening of the body element would like this:

<body class="default news get">

There are some limitations. For example, you need to be careful not to overlap module, controller, or action names. If this is a problem for you then you could preface the class names (e.g. module-default, controller-news, action-get).

The RouteContext plugin hooks into the preDispatch event and creates an array of route context strings. This example simply uses the module, controller, and action names as the route context. Often I'll add other contextual strings to this array as needed. This array is then assigned to the view. The layout view script then simply implodes this array into the value of the class attribute using a space character as the glue.


marsbomber said...

Hi Bradley, I was wondering about the needs of this plugin when I was studying your Postr sample app. I'm wondering if I could get away with using a view helper? What are the pros and cons?

bradley-holt said...

@marsbomber Interesting, I hadn't thought of doing it as a view helper instead. I like it: simply pull the current module, controller, and action names in the view helper as needed. No need to pass around another parameter.