Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, January 11, 2010

Zend Framework Route Context Plugin

See Zend Framework Route Context Plugin at its new home on bradley-holt.com.

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.