Switching layout using a url parameter

I needed to open a static page in a pop-up window. For static pages we have a handy controller Pages but I wanted to use a different layout for each page and do it in a flexible way.

The magic of my solution is in three lines of code in AppController (app/app_controller.php). I simplify the code for the sake of clarity:

  1. class AppController extends Controller {
  2.   function beforeFilter() {
  3.     if (!empty($this->passedArgs[‘layout’])) {
  4.       $this->layout = $this->passedArgs[‘layout’];
  5.     }
  6.   }
  7. }

I created a file /app/views/layouts/popup.ctp that contains only:

  1. <?php echo $content_for_layout; ?>

And I call the static page as:

  1. http://test.com/pages/termsOfMembership/layout:popup

Which is created using this call:

  1. $html->link(
  2.    ‘Terms of Membership’,
  3.    Router::url(array(‘controller’ => ‘pages’, ‘action’ => ‘termsOfMembership’, ‘layout’ => ‘popup’)),
  4.    array(
  5.      ‘default’ => false,
  6.      ‘onclick’ => "window.open(this.href);")
  7.    ),

With this setting in my /app/config/routes.php:

  1. Router::connect(‘/pages/*’, array(‘controller’ => ‘pages’, ‘action’ => ‘display’));

That Router setting is redundant if you use urls that look like this:

  1. http://test.com/pages/display/termsOfMembership/layout:popup

Then you also have to use a different call to the Router::url():

  1. array(‘controller’ => ‘pages’, ‘action’ => ‘display’, ‘termsOfMembership’, ‘layout’ => ‘popup’)

Leave a Reply