Replicating Rails RJS in CakePHP
Article posted by Joel Moss on 03 Jan 2007   |  
One of the things that I like so much about the Ruby on Rails framework are its RJS templates. I will let the Rails API tell you more:
Unlike conventional templates which are used to render the results of an action, these templates generate instructions on how to modify an already rendered page. This makes it easy to modify multiple elements on your page in one declarative Ajax response. Actions with these templates are called in the background with Ajax and make updates to the page where the request originated from.
So when you make an Ajax call, you can return pure javascript and use that to modify the page that you are on. For example, you could create an RJS template that simply hides an element on the page you are on. Replicating RJS templates in CakePHP is surprisingly easy with the all new 1.2 version of the rapid application development framework for PHP. All you gotta do is add the following function in your AppController:
function beforeRender()
{
    if (isset($this->params['url']['ext']) && $this->params['url']['ext'] == 'js')
    {
        $this->layout = false;
        header("Content-type: text/javascript");
    }
}
What that does is take advantage of the new URL Extensions introduced in CakePHP 1.2. It looks to see if you are using a JS extension. If you are, it disables the layout and sets the pages Content-Type to "text/javascript". Now when you call http://MyCakeApp/controller/action.js it will return your Javascript template from /app/views/controller/js/action.ctp. This view template should contain only javascript, but of course you can still use PHP and your Helpers in there. It will also only work if you are using the Ajax functionality of the Prototype javascript library. So the following could be the entire contents of your JS view:
  new Effect.Highlight('');
  Field.activate('');

    $('loading-text').update('Login Successful.');
    window.location.href = '/';
As you can see, you don't need to use any SCRIPT tags. Just place the javascript directly into it. Works a treat and does exactly what Rails RJS templates do. Please do try it and play with it some more, as you won't really know its full potential until you do.

This site contains the musings of Joel Moss, and is powered by Codaset pages; a simple, yet powerful way to host your static site. Just commit and push your site to your free Git repository at Codaset, and that's it!

Tell me more about Joel »