Store
Community Documentation

v3 Knowledgebase

Add Javascript and CSS files to your pages

In this article we will learn how to include Javascript and CSS files in the header of the html page.

For this we need to have a controller, so if you are unsure about how to create a controller here is a kick start.

In this case we need to modify what is inside the process() function in the controller, in fact for most cases when working inside a controller php file you only need to edit inside the process() function.
So, inside a controller we have access to the template library, let suppose now that our controller is in the folder /module/mymodule/include/component/controller/example.class.php and that we want to use our own javascript code in this page, first make sure that you have the folder
/module/mymodule/static/jscript/

and then create your javascript file there, for example
/module/mymodule/static/jscript/mycontroller.js

Now to include this javascript file all we have to do is this:
PHP:
$this->template()->setHeader(array(
  
'mycontroller.js' => 'module_mymodule'
)); 


So the controller would look similar to this:
PHP:
<?php

class Core_Component_Controller_Example extends Phpfox_Component
{
    public function 
process()
    {
        
$this->template()->setHeader(array(
                
'mycontroller.js' => 'module_mymodule'
        
));
    }
}
?>


In that array, "mycontroller.js" is clearly the name of the file we want to include, and the second part, the "module_mymodule" is our way of telling the phpfox script where to find this file.

For CSS it is only a little different since the CSS depends on the theme and style in use, if you are using the default theme and style then you would have the CSS file in:
/module/mymodule/static/css/default/default/mycontroller.css

Please notice that the names of the files can be anything you want, I used these only as examples but you can name them "myotherfile.css" if you want, as long as you write it properly in the controller.

Another thing to consider is if you want to add straight javascript code in the header, you can easily do that from the controller:
PHP:
$this->template()->setHeader(array(
                
'<script type="text/javascript"> $(document).ready(function(){ alert("Helo!"); });'
)); 


Finally, another case is if the file is in the /static/jscript folder, we use this folder for scripts that are used in several locations, thus they dont belong to one specific module, like the flash mass uploader. These are files in the /static/jscript folder and you can include them like this:
PHP:
$this->template()->setHeader(array(
                
'progress.js' => 'static_script'
)); 


Now, since setHeader receives an array we can mix it up all in one single call:
PHP:
$this->template()->setHeader(
                
'progress.js' => 'static_script',
                
'<script type="text/javascript">var sString = "Hello";</script>',
                
'mycontroller.js' => 'module_mymodule'
);