JavaScript Code Block in Cake
Sometimes you need to trigger javascript functions or set variables in a view. With JavaScriptHelper, you do not have to print out the <script> tags. All you’ll need is calling a JavaScriptHelper function called codeBlock() function. The <script> tags will be generated itself and a CDATA too if you want it.
Make sure you have added JavaScriptHelper in your Controller where you’ll need the function.
In controller :
$helpers=array(’JavaScript’);
Method codeBlock($string=null, $options=array());
$string = JavaScript codes to be wrapped in <script> tags
$options = There are two parameters, $safe (boolean) and $allowCache (boolean)
The default value of $options['safe'] is true which means “it wraps the script in an HTML comment and a CDATA block”. You can set to false if you do not need it.
I still do not understand using the $allowCache. Please read the API.
Usage example :
In view :
<?php
$script=”alert(’hello world’);”;
echo $javascript->codeBlock($script);
?>
The result is :
<script type=”text/javascript”>
//<![CDATA[
alert('hello world');
//]]>
</script>
I hope it helps somebody…
cheers!
Nicolas said:
Sep 23, 08 at 11:05 pmMmmm I just read myself and I don’t think I was clear
What I actually want to know is, using the code I provided, how would I do to use the codeBlock function inside it?
echo $form->input(’question1′, codeBlock($script)…
Hope it’s clearer now!
Thanks again
Seandy said:
Sep 24, 08 at 9:04 amHi Nicolas,
I think you can’t use $javascript->codeBlock in $form->input options, but you can set your javascript attributes.
For example :
input(”variablename”,array(”onFocus”=>”alert(’Focus’);”,”onMouseOut”=>”alert(’Out’);”));
?>
Output will be :
Hope it helps you.
Nicolas said:
Sep 24, 08 at 6:07 pmThank you Seandy, I will try as you said, it should do the trick!