NaszvadiG
4/17/2014 - 9:04 AM

CI - Assets Controller

CI - Assets Controller

<?php

// Insert the following into `application/config/routes.php` (put these above the others)
$route['assets/([a-z_-]+)\.[a-z]+$']          = "assets/index/$1";
$route['assets/([a-z]+)/([a-z_-]+)\.[a-z]+$'] = "assets/index/$1/$2";
<?php
// This is a sample CSS File
// Place this at `application/views/assets/css/myStyle.php`
// Navigate the browser to `assets/css/myStyle.css` to get the output.
?>
.box {
    display: block;
    width: 100px;
    height: 100px;
    margin: 0 auto;
    background: #fff url(<?php echo base_url('images/bg.png'); ?>);
}
<?php
// This is a sample JavaScript File
// Place this at `application/views/assets/js/jsFile.php`
// Navigate the browser to `assets/js/jsFile.js` to get the output.
?>
$('#example').dataTable({
    "bProcessing": true,
    "sAjaxSource": "<?php echo base_url(); ?>"
});
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter Assets controller
 *
 * @author      Hashem Qolami <hashem@qolami.com>
 * @copyright	2013 Hashem Qolami
 * @license  	http://opensource.org/licenses/MIT (MIT license)
 */
 
class Assets extends CI_Controller
{
    /**
     * Checking file existance
     * 
     * @param  string $dir  file sub-directory
     * @param  string $file file name
     * @return string       view path
     */
    private function _checkFile($dir = '', $file = '')
    {
        if ($file === '') {
            $file = "assets/$dir";
        } else {
            $file = "assets/$dir/$file";
        }

        if (! file_exists(APPPATH . 'views/' . $file . '.php')) {
            show_404($this->uri->uri_string());
        }

        return $file;
    }

    /**
     * Generate asset file
     * 
     * @param  string $file file name
     * @param  string $ext  file extension
     * @return void
     */
    public function index($ext = '', $file = '')
    {
        $file = $this->_checkFile($ext, $file);

        $file = $this->load->view($file, '', TRUE);

        $this->output
            ->set_content_type($ext)
            ->set_output($file);
    }
}