Linking External Style Sheets In CodeIgniter
11.04.2007 | My Blog
Having been working with CodeIgniter for about two years now, I have always struggled with how to structure my themes. This past week I came up with what seems to be such an obvious solution for external css handling in CodeIgniter, that I was surprised I haven’t read about it elsewhere. Perhaps it’s so obvious that most felt it need not to be mentioned, however I would have loved to come across something like this long ago.
Before I start, credit must be given for my inspiration to the Rapyd dev team. A lot of where I got this process from was due to how Rapyd has it’s samples set up in it’s distribution. The Rapyd samples pre-load a view filled with css and then plants it inline into the final view that is outputted. I liked the idea of having my css organized with my views, but didn’t want it inline with the rest of the html. Here’s how linking it externally can simply be done…
First set up a controller, maybe say named ‘themes’, and inside that controller we will set up a ’style’ function. First in that style function were going to set the header and tell the browser that this will be a style sheet. It’s very important you do this, otherwise the browser should disregard it, or at least I know in Firefox it will. Next we’ll call the view containing the css.
class Themes extends Controller {
function index () {
//do something
}
function style() {
$this->output->set_header("Content-type: text/css");
$this->load->view('themes/style');
}
}
Now we will just call this controller from our final output view, or however you have your views embedded, in a link statement in your head area like so…
<link href="http://mysite.com/themes/style" rel="stylesheet" type="text/css" />
An alternate way of doing this…
function style() {
header("Content-type: text/css");
echo $this->load->view('themes/style', null, true);
}
However this method seems a little redundant to just use only a part of CodeIgniter’s abilities. But it might show someone how to apply this method in an regular php application. Douglas Clifton has a good article at Digital Web Magazine on doing it the non-CodeIgniter “style”.
Of course their is much more functionality you could add to your themes controller, but going into all that is beyond what I wanted to do here. Theme changing and adding dynamic variables within your ‘css’ views are just a start, and my meager little mind is thinking of many others, if I play with it more I’ll let ya know how it goes.
1.25.2008
well done and thanks - this was of help