Let’s take a quick look at how this applies to CakePHP and what (hopefully) useful tricks you can accomplish by employing the following techniques…
We’ll create an empty view (views/users/test.ctp), for the sake of this demonstration and load some JS file:
Having the “.js.php” in the name of the file prevents cake from tacking on the “.js” extension by default, therefore our include in the head looks as we’d expect:
Now, wouldn’t it be lovely to pass some variables from our Users Controller to this file?
Alright, let’s build a simple test() action:
$this->Session->write('User', 'My name is Charlie');
Since we are actually serving up a PHP file, rather than a plain JS file… we can blend JS and PHP to make some interesting things happen.
Here’s our test_file.js.php:
session_name(‘CAKEPHP’); is based on the session cookie name, which is set in config/core.php.
The rest of the file should pretty much self explanatory… we simply pop-up an alert box with “My name is Charlie”, which we’ve wrote to the session in the Users Controller above.
(Sorry, I couldn’t come up with a more boring example).
However, this opens up some interesting opportunities, such as dynamically setting values for your jQuery scripts, while maintaining very clean mark-up and avoiding any in-line JS.
P.S. AD7six pointed out that any .js file in your app/vendors/js/ can have PHP code in it, so you don’t need to use “.js.php” trick, however many IDE’s will give you a very quirky highlighting (to say the least) when you are editing PHP code in a .js file, but not the other way around. Either way you’ve got both options to play around with.