A new "automagic" for CakePHP layouts with the CustomLayouts component

By Filippo Toso (filippo.toso)
If you distribute your CakePHP web application to others and they ask you how to personalize the layout of a specific controller or, with even more granularity, a specific action, what do you do? This component creates a new convention for layouts that lets you automagically personalize the layouts for controllers and single actions with one line of code.
Adding this component to the $components property of your controller (or AppController) enables the following convention:

  • if exists, use the views/layouts/{controller}/{action}.ctp layout, otherwise
  • if exists, use the views/layouts/{controller}.ctp layout, otherwise
  • use the layout defined by the controller

This component is usefull if you want to make your web application "customizable" (from the UI point of view), but you don't want to hardcode the layout names in your controllers' source code.

The convention is "executed" before the controller's beforeFilter() method so you can override it in case of necessity.

Component Class:

Download code <?php 
/**
 * PHP versions 4 and 5
 *
 * Custom Layouts Component: A component that introduces a new convention for CakePHP layout files
 * Copyright 2007-2008, Creative Park Srl
 *                      Borgo Acquileia, 3/f
 *                      33057 Palmanova (UD) Italia
 *                      http://www.creativepark.it/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

class CustomLayoutsComponent extends Object {

    function 
initialize(&$controller) {
        
$action Inflector::underscore($controller->action);
        
$name Inflector::underscore($controller->name);
        
$file LAYOUTS $name DS $action $controller->ext;
        if (
file_exists($file)) {
            
$controller->layout $action;
            
$controller->layoutPath $name;
        } else {
            
$file LAYOUTS $name $controller->ext;
            if (
file_exists($file)) {
                
$controller->layout $name;
                
$controller->layoutPath NULL;
            }
        }         
    }

}
?>


P.S. This is my first component and I'm not even sure this convention already exists :)

 

Comments 840

CakePHP Team Comments Author Comments
 

Comment

1 nice

Nice idea and well implanted. Good job. If I ever have a need for this i'll come back.
Posted Nov 4, 2008 by Jonah Turnquist
 

Comment

2 An interesting idea

Well done, I'm sure this will be handy in the future ;)
Posted Nov 7, 2008 by Hannibal Lecter
 

Comment

3 cakephp themes

really convenient thing to have in some projects, just one notice it does not consider usage of themes and layouts that they contain.
Posted Jan 17, 2009 by Rytis