CakePHP’s $javascript helper is useful but it can be somewhat fickle.
I wanted to throw my javascript into $scripts_for_layout so it’d be in the head of the page. That’s what codeBlock is supposed to do. It seems like you get a couple of usage options. You can write all your javascript as a string and pass it as the first argument or you can (this is what it seems, it’s purely speculative) use codeBlock and blockEnd and allow CakePHP’s buffering magic to capture the javascript between your php tags.
Here’s what I was trying for a while.
$javascript->codeBlock('window.addEvent("domready", function(){alert("hi there);});');
I refresh and cleared my cache but I never did find my code in the head. I noticed an option called inline. It’s set to true by default. So there’s something I can do! I can set that option to false.
$javascript->codeBlock('window.addEvent("domready", function(){alert("hi there);});', array("inline" => false));
I passed in an array with inline:false and that actually worked. It printed my code out after my other javascript that was already included on the page. The lesson here was that in order to get codeBlock to print something, you must set inline to false. blockEnd isn’t used with this method, which I thought was odd too.
I’m happy to mention that in CakePHP 1.3 the javascript helper will be overhualed.
Hi Ryan
yes, I can never remember the syntax for this off the top of my head! (and the CSS equivalent). What I often do is to make the code more redable, put the Javascript statement in a heredoc syntax in PHP
e.g
$js = <<<MYJS
/* all this is javascript */
var foo = bar;
// etc
MYJS;
so then you can just popo the $js variable in the cake codeBlock() call.
I find web developing easier if I can keep things clean and ordered like this.
Anything really long should pretty much go in an external javascript file, named consistently – so much design is just good conventions I realise…
Ryan,
if you use (the default)
array(“inline” => false)
then $javascript->codeBlock() is returning the codeblock, but not echoing it. Thus you need to add an “echo” in front of it.
codeBlock(‘window.addEvent(“domready”, alert(“hi there 2″));’); ?>
works fine in your view.
Regards,
Kalileo
hmmm, and it has eaten the
echo $form-> in front of it too :s
let’s try again:
echo $form->codeBlock(‘window.addEvent(“domready”, alert(“hi there″));’);
echo $form->codeBlock(‘window.addEvent(“domready”, alert(“hi there″));’);
Should be
echo $javascript->codeBlock(‘window.addEvent(“domready”, alert(“hi there″));’);