Codeigniter: How to include javascript files

Viewed 98802

Hello I just started working with CodeIgniter framework. My current directory structure is

Demo(Project name)
 +System
 +Application
   -Controllers
      demo.php
   +Model
   -Views
      view_demo.php
 -Js
    ajax.js
    jquery.js  

Please tell me how to include .js files in view_demo.php.

Thanks Raj

6 Answers

The $data variable sometimes may be lost if you have nested views and you don't pass it as an argument to the children/nested views.

I found a simple solution that is working very smoothly to me:

In your current view file you setup your script like this:

$this->scripts[] = '/js/myscript.js';

at your footer or {whatever.php} file you insert this code:

    <?php
        if(isset($this->scripts))
        foreach($this->scripts as $script) :
     ?>
            <script src="my_asset_path/js/<?=$script;?>"></script>
    <?endforeach;?>

If you need only a pice of javascript code, you can always use anonymous functions like this:

<?php
$this->RenderScript[] = function() {
?>
      <script>
        console.log('myjavascript code snippet');
      </script>
<?}?>

and at the bottom:

<?php
        if(isset($this->RenderScript))
            foreach($this->RenderScript as $script) {
                $script();
            }
    ?>
Related