CodeIgniter Forums
Loading CSS With PHP Extension From Within Controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Loading CSS With PHP Extension From Within Controller (/showthread.php?tid=45620)



Loading CSS With PHP Extension From Within Controller - El Forum - 09-28-2011

[eluser]J. Pavel Espinal[/eluser]
Hello Folks,

I ran into a situation where I wanted to load a dinamyc generated CSS.
After some wrestling with the code, I got to this solution:

Note: it is not the best solution, maybe not even a good one, but it worked.

1. I created a CSS controller that will handle the file name (and, in a future, compression, if you want)

css.php file (CSS loader)

Code:
class Css extends CI_Controller {
    
    /**
     * Class Constructor
     */
    public function __construct() {
        parent::__construct();
    }
    
    
    /**
     * Default Index
     *
     * @return string
     */
    public function index() {
        return '';
    }
    
    
    /**
     * Css Loader
     *
     * @param string $asFileName
     */
    public function load($asFileName='') {
        
        if(empty($asFileName)) {
            return;
        }
        
        $lsFileExt  = pathinfo($asFileName, PATHINFO_EXTENSION);
        
        if($lsFileExt != 'css') {
            log_message('error', 'There was an attept to load a non css file');
            return;
        }
        
        header('Content-Type: text/css');
        $this->load->view('css/' . $asFileName . '.php');
    }
}


2. Now, in your view, you could use something like:

Code:
<link rel="stylesheet" href="<?=site_url('css/load/screen.css')?>" type="text/css" media="screen" title="default" />

In the previous example, my css file is called: screen.css.php, and is located at [views]/css/

Note that the "header('Content-Type: text/css');" part is essential.


I hope this helps someone Smile

Regards,