Welcome Guest, Not a member yet? Register   Sign In
Load CSS/JS dynamically in header.php depending on current view
#1

[eluser]Unknown[/eluser]
I searched around a little and didn't find any good solutions for this, but I'd like to load up CSS files in views/templates/header.php depending on which view I'm on.

For example, my directory structure is as follows:

<pre>
views
--- account
--- dashboard
content
--- css
------ app
--------- account
------------ index.css
--------- dashboard
------------ index.css
</pre>

So if I make the following request: http://localhost/account/settings

... I want to be able to load my CSS file located at content/css/app/account only. Likewise, if I hit my dashboard view I only want to load the CSS located at content/css/app/dashboard. Within header.php I'd be generating the include something like this:

Code:
&lt;link rel="stylesheet" type="text/css" media="screen" href="content/css/app/$view/index.css" /&gt;

... where $view is the current view that I'm on.

My JS is structured similarly and I'll be loading that from views/templates/footer.php.

Suggestions? I know this is probably simple but a big brain fart at the moment.
#2

[eluser]TheFuzzy0ne[/eluser]
Welcome to the CodeIgniter forums!

Personally, I use a main template, and a library I call doc_head. If I need to add any CSS or script to the view, I simply add it through the library, and call $this->doc_head->output() from within my main template, and it appears. It's useful for dynamically inserting stylesheets, meta data and scripts.

Basically, all you need is a variable which you feed into the view, which your main template checks for, and echoes if it's set.
#3

[eluser]Unknown[/eluser]
Interesting. I'll explore that approach further as I get more time.

For the meantime, I've accomplished what I originally set out to do by creating a property named $view in my controllers that contains the name of the view. The only downside to this is that each of my controllers has to contain this property but that's a minor issue.

Within my header I can now output my CSS as follows:

Code:
&lt;link rel="stylesheet" type="text/css" media="screen" href="&lt;?php echo base_url();?&gt;content/css/app/&lt;?php echo $this-&gt;view; ?&gt;/index.css" /&gt;

Within my footer I can likewise output the appropriate script file as follows:

Code:
&lt; script src="&lt;?php echo base_url();?&gt;content/js/app/&lt;?php echo $this-&gt;view; ?&gt;/index.js"&gt;&lt; /script>

Of course this approach only works under the assumption that each view has a single JS and CSS file, but I could easily define an array property that includes several files and output those in a loop.
#4

[eluser]TheFuzzy0ne[/eluser]
Neat approach. I guess that brain fart cleared? Smile
#5

[eluser]Otemu[/eluser]
Here is a similar question asked although not exactly the same as yours thought it my prove useful http://ellislab.com/forums/viewthread/233286/




Theme © iAndrew 2016 - Forum software by © MyBB