Referencing Javascript files

Published on February 21, 2007 and tagged with cakephp  javascript

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);

That’s it.

38 comments baked

  • nate February 21, 2007 at 19:30

    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 February 21, 2007 at 20:05

    @nate: Thanks for the additional tips :)

  • Aphex February 21, 2007 at 20:52

    Thank you for great tips! :)

  • Dieter@be February 21, 2007 at 23:29

    perfect :)

  • Walker Hamilton February 22, 2007 at 21:11

    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 February 23, 2007 at 13:32

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

  • cakebaker February 23, 2007 at 17:11

    @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 March 14, 2007 at 12:42

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

  • jiri April 12, 2007 at 13:15

    I wrote a small helper for automatically including JS and CSS files, following Cake’s “convention over configuration”. You can check it out at http://jirikupiainen.com/2007/04/11/automatically-loading-js-and-css-files-with-cakephp/ if you’re interested – I’d love to get some feedback.

  • cakebaker April 12, 2007 at 19:03

    @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 September 28, 2007 at 16:54

    [...] 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 February 04, 2008 at 10:53

    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 February 04, 2008 at 18:01

    @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 February 06, 2008 at 11:26

    Sorry for the confusion – I got distracted by the docblock ‘$url String URL to JavaScript file [...]‘, http://api.cakephp.org/1.2/javascript_8php-source.html#l00138 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 February 06, 2008 at 18:43

    @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 February 24, 2008 at 12:07

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

  • Ahmed Kamel March 11, 2008 at 09:05

    Hi

    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/rounded_corners.inc.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?

    Thanks

  • cakebaker March 11, 2008 at 17:24

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

  • Ahmed Kamel March 12, 2008 at 10:01

    @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”)) ?>

    Thanks

  • cakebaker March 14, 2008 at 19:40

    @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 April 27, 2008 at 01:08

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

    link(‘cities.js’);
    endif;
    ?>

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

    Thanks

  • G Bruno April 27, 2008 at 01:10

    Oops this is the snippet.

    if(isset($javascript)):
    $javascript->link(‘cities.js’);
    endif;

  • cakebaker April 27, 2008 at 10:41

    @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');
    
    or 
    
    var $helpers = array('Javascript'); // PHP 4
    

    Hope that helps!

  • Amir May 26, 2008 at 10:04

    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 May 26, 2008 at 17:13

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

  • CombatWombat July 28, 2008 at 14:37

    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

    Followed:http://bakery.cakephp.org/articles/view/using-tinymce-with-cakephp
    and http://bakery.cakephp.org/articles/view/using-tinymce-with-cakephp-and-ajax

    What am I doing wrong?

  • cakebaker July 29, 2008 at 16:21

    @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 April 29, 2009 at 16:32

    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 April 29, 2009 at 16:35

    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 April 29, 2009 at 16:44

    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 May 01, 2009 at 08:22

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

  • Mr Speaker June 01, 2009 at 04:40

    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?

    Thanks!

  • cakebaker June 01, 2009 at 09:22

    @Mr Speaker: Thanks for your comment!

    I hope I could answer your question with the following article: http://cakebaker.42dh.com/2009/06/01/specifying-helpers-for-static-pages/

  • Danish June 07, 2009 at 15:33

    Hey

    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 danish.don123@gmail.com

    I really need to know please help me out guys…

    Regards,

  • cakebaker June 08, 2009 at 16:06

    @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 http://bin.cakephp.org?

  • Imran August 12, 2009 at 11:55

    Thanks a lot.

  • AngryJoe June 17, 2010 at 20:56

    Well done. That was a big help.

  • cakebaker June 21, 2010 at 15:54

    @AngryJoe: You are welcome!

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License