Monday 26 January 2009
Facebook StumbleUpon Twitter Google+ Pin It

How to Include Javascript File in Cake PHP

If you want to use a Javascript file, you usually reference it in the head section of your layout:

<head>
    <?php echo $javascript->link('script.js'); ?>
</head>

But sometimes you want to use a certain Javascript file only in one view. Then it doesn’t make sense to reference it in the layout. You could take the PHP statement from above and place it in your view, that will work. But it is not a clean solution as the Javascript reference is placed somewhere in the middle of the generated HTML code.

Fortunately, CakePHP 1.2 allows you to define a reference to a Javascript file which is then added to the head section of the generated HTML code. For this purpose the variable $scripts_for_layout has to be added to the layout:

<head>
    <?php echo $scripts_for_layout; ?>
</head>

In the view you can now link to the Javascript file with:

$javascript->link('script.js', false);

Notice the second parameter. Set it to false to tell cake to put the reference in $scripts_for_layout variable in the layout file.



Parthiv Patel
Bhaishri Info Solution
Sr. PHP Developer
Limdi Chowk, AT PO. Nar, Di. Anand
Nar, Gujarat
388150
India
pparthiv2412@gmail.com
7383343029
DOB: 12/24/1986

No comments: