Referencing Javascript files

Published on and tagged with cakephp  javascript

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

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

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:

    <?php echo $scripts_for_layout; ?>

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

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

That’s it.

42 comments baked

  • nate

    FYI, you don’t actually need to include the ‘.js’, since it is added to the file automatically, so you can also do $javascript->link(‘script’);

    Another feature that’s new in 1.2 is the ability to specify mutliple scripts in a single link() call, i.e. $javascript->link(array(‘script1’, ‘script2’));

  • cakebaker

    @nate: Thanks for the additional tips :)

  • Aphex

    Thank you for great tips! :)

  • Dieter@be

    perfect :)

  • Walker Hamilton

    This is excellent. A feature that I _sort of_ self-implemented but that I knew could be done better.

    now it has been.

  • Digital Spaghetti

    Is this version 1.2 only, I’m currently working with 1.1

  • cakebaker

    @Digital Spaghetti: Yes, it is 1.2 only. With 1.1 you have to use something like the HeadHelper, which is available in the snippet section on CakeForge.

  • cakebaker » Referencing CSS files

    […] time ago I wrote a post titled “Referencing Javascript files” in which I explained how you can reference Javascript […]

  • jiri

    I wrote a small helper for automatically including JS and CSS files, following Cake’s “convention over configuration”. You can check it out at if you’re interested – I’d love to get some feedback.

  • cakebaker

    @jiri: Looks good, but at least for me it is rather seldom that I use controller resp. action specific CSS and JS files.

  • cakebaker » How to write and test your own head helper

    […] section of a HTML page from the view. CakePHP 1.2 provides such a functionality for referencing Javascript and CSS files. If you want to add something else to the head section, you have to write your own […]

  • ben

    Be wary of using js file names with dots in it, e.g. jquery-1.2.2.min.js as this will screw the routing. This results in in a javascript error since cake then tries to find a ‘JsController’ as it doesn’t look in the /app/webroot/js folder any more.
    You’ll notice it in form of a js syntax error because instead of the js the default error html page gets included.
    Workaround: don’t use dots in your file names.

  • cakebaker

    @ben: Hm, I’m using it to reference the jquery library, too. But I didn’t encounter any problems, it’s working here with the beta version and the latest version from the repository.

  • stupid ben

    Sorry for the confusion – I got distracted by the docblock ‘$url String URL to JavaScript file […]’, and tried every possible path syntax (e.g. ‘js/jquery-1.2.2.min.js’) except for the (right) one without leading path info and trailing file extension.
    Working syntax: $javascript->link(‘jquery-1.2.2.min’) if your jquery script resides in /app/webroot/js that is.

    update: $javascript->link(‘jquery-1.2.2.min.js’) works like a charm too – I don’t know how I even got to write that nonsense comment. Many thanks for checking though and sorry for the bogus error report.

  • cakebaker

    @ben: No problem. I think your comment simply showed that the specific doc block could be improved. So I opened a ticket for it.

  • Edit in place with JQuery and CakePHP - cakebaker

    […] use the Javascript files, we have to include them in the layout (or in the view, see “Referencing Javascript files” for more […]

  • Ahmed Kamel


    Ben, I am not sure if you are as crazy/stupid as you think you are :) I am trying to do the same thing, and it seems that I cannot include a .js file if it has a period in its name. I try navigating to the url localhost:8080/js/ and it doesn’t work. If I look for hello.js it works fine. The periods are doing something to it! Any idea what is wrong. Or am I crazy too?


  • cakebaker

    @Ahmed: How do you reference the .js file and where is the .js file located?

  • Ahmed Kamel

    @cakebaker: well regardless of how I reference them, they don’t seem to work at all right now :)

    If I have foo.js in app\webroot\js\ and try to access localhost:8080/js/foo.js I get error 403. I am wondering if this is a router problem. or .htaccess…

    This is running apache 2.2 on Windows Vista; Everything works fine, and the front page works well (all colors/css showing).

    But, when I want to print a script tag I do: link(“bubbles/rounded_corners_inc.js”)) ?>


  • cakebaker

    @Ahmed: Hm, it’s a bit strange that you get a 403 error. Does the web server has the permissions to read that file? And is the link to the javascript in the HTML file? But I have to admit I’m a bit in the dark ;-)

  • G Bruno

    I am trying to reference my js file in my head tag by doing the following:


    But I get an error saying that the $javascript variable is undefined. Can someone explain where I set this variable with an example?


  • G Bruno

    Oops this is the snippet.


  • cakebaker

    @Bruno: You have to add the Javascript helper to the $helpers array of either your controller or your AppController (app/app_controller.php):

    public $helpers = array('Javascript');
    var $helpers = array('Javascript'); // PHP 4

    Hope that helps!

  • Amir

    I am writing the code
    echo $javascript->link(‘soft.js’); in the view part, but can not access the file through it, nor can I access the .css files by $html->css(‘css_name’);
    on my controller I have
    var $helpers = array(‘Html’,’Javascript’);
    Any help will be appreciated.

  • cakebaker

    @Amir: Is there an error displayed? And if you look at the generated HTML, does it contain the links (maybe with wrong paths)?

  • CombatWombat

    I have the same problem as Amir. New to Cake. Version: CakePHP1.1.19.6305.
    Trying to get my head around MVC, and that is great stuff, but current snag is adding AJAX, specifically tiny_mce to the mix.
    My resultant page source shows:/cake/js/tiny_mce/tiny_mce.js
    It should be /cake/app/webroot/js/tiny_mce/tiny_mce.js


    What am I doing wrong?

  • cakebaker

    @CombatWombat: Hm, no idea why you get a wrong path… Personally, I would point the document root to app/webroot, and the problem should go away ;-)

    Btw: As you are new to Cake, I would directly start with CakePHP 1.2.

  • pokaru

    Although I’m linking many .css and .js files using:

    $html->css(‘sheet.css’); and $javascript->link(‘script.js’);

    when I echo $scripts_for_layout, I get the empty string.

    Can anyone help?

  • pokaru

    The $scripts_for_layout variable is always null.

    I’ve linked a few js files via $javascript->link(‘script.js’), but I get nothing. Can anyone help?

  • pokaru

    Nevermind :D.

    I just figured out that I need to specify ‘false’ as the second parameter for the $javascript->link() method. Setting that parameter to false will cause the script you’re trying to link to show up wherever $scripts_for_layout variable is specified.

  • cakebaker

    @pokaru: I’m glad you found the solution in the meantime :)

  • Mr Speaker

    What about for staticpages in /views/pages/? You can’t add the JavaScript helper, because there isn’t a controller – how can I add javascript files in pages?


  • cakebaker

    @Mr Speaker: Thanks for your comment!

    I hope I could answer your question with the following article:

  • Danish


    I need to ad my Google ads to the cakephp default layout…..

    If I add the code directly like we add in any html page it doesnt appear…

    I also tried both of the tricks shared here but its not working..

    Kindly help me and email me at

    I really need to know please help me out guys…


  • cakebaker

    @Danish: Hm, I don’t see why it shouldn’t work if you put the adsense code directly to the layout. Can you paste your code somewhere, for example on

  • Imran

    Thanks a lot.

  • AngryJoe

    Well done. That was a big help.

  • cakebaker

    @AngryJoe: You are welcome!

  • Axel

    Hi, i’m using the 1.2 version, and i have to use a javascript in my view, i wrote
    link(‘/calendar/dhtmlgoodies_calendar/dhtmlgoodies_calendar.js?random=20060118’); ?>
    on the top of the code, but when i acces the page and the next erro appears

    Notice (8): Undefined variable: javascript [APP\views\appointments\cita.ctp, line 1]

    Fatal error: Call to a member function link() on a non-object in C:\xampp\htdocs\cmc\views\appointments\cita.ctp on line 1

    any ideas about why is not working?, i’m kinda new with cakephp
    thanks in advance

  • Axel

    “link(‘/calendar/dhtmlgoodies_calendar/dhtmlgoodies_calendar.js?random=20060118’); ?> ”
    without the quotes

  • Axel

    well i don’t know why it keeps deleting the string,

  • cakebaker

    @Axel: To use the JavaScript helper in your view, you have to add it to the $helpers array of your controllers like so:

    class ExamplesController extends AppController {
        public $helpers = array('Javascript');

    Hope this helps!

© daniel hofstetter. Licensed under a Creative Commons License