Saturday, 25 June 2011

Loading CSS, JS and images from CodeIgniter

Just a quick tip for newbs (me included). If you're having trouble loading css, js or image files into your views/templates in CodeIgniter and you do a Google search to find the solution, you'll find many websites telling you to use the base_url() function. This didn't work for me!

The reason why it didn't work was because I hadn't loaded the url helper class... DUH! Stick this in the constructor of your controller or autoload it in your autoload.php configuration file.

$this->load->helper('url');

Now you can use the base_url() function to get the url path from where to look for those files, e.g.:

<link rel="stylesheet" href="<?php echo base_url(); ?>styles/main.css" type="text/css">

This will load a css file called main.css from a folder called styles which is just under the base url folder codeigniter. On my PC it will find the file from: C:\wamp\www\codeigniter\styles\main.css

I reckon the creators of CodeIgniter should have added a constant through which to refer to the base_url and similar paths, or at least make the url class have static functions so url::base_url() can be called instead of base_url() which could be confused for a normal PHP function.

4 comments:

  1. it still doesn't work ;)

    ReplyDelete
  2. That is good information about Loading CSS, JS and images from CodeIgniter , it is useful to me thanks.

    ReplyDelete
  3. thx verymuch :)

    ReplyDelete