Use Assetic with CodeIgniter

Assetic is an excellent asset management library by Kris Wallsmith. You can use Assetic is to combine and minify CSS/JS files, compress images, process SCSS/Sass files and much more.

This tutorial will guide you through installing Assetic and using Assetic with CodeIgniter. Basically, I will show you how to load multiple CSS files and convert them into a single static CSS file using Assetic.

Install Assetic

I am assuming that you already have CodeIgniter installed . Open a terminal (or command prompt), navigate to your "application" folder and input the following command:

composer require kriswallsmith/assetic

This will install assetic in your application/vendor folder.

Load Assetic in CodeIgniter

Edit application/config.php file and set "composer_autoload" setting to true. Enabling this setting will tell CodeIgniter to load the Composer auto-loader script from application/vendor/autoload.php

Now you are ready to start using Assetic in your CodeIgniter app.

Load CSS Files

See below for minimal code you will need to load CSS files and combine these into a single static CSS stylesheet that you can then use in your HTML code.

//Create an AssetCollection
$css = new Assetic\Asset\AssetCollection();

//CssRewriteFilter will fix the relative URLs in your CSS styles $css->ensureFilter(new Assetic\Filter\CssRewriteFilter());

/*
* Add your CSS stylesheets to the AssetCollection. The paths could
* be either absolute, or they could be relative to your index.php file
*/
$css->add(new Assetic\Asset\FileAsset('assets/css/bootstrap.min.css'));
$css->add(new Assetic\Asset\FileAsset('assets/css/styles.css'));
$css->add(new Assetic\Asset\FileAsset('assets/css/responsive.css'));

Create Static CSS File

The above code will load the specified CSS files. Now you can get Assetic to combine these multiple CSS files into a single static CSS file. Use the below code to generate a combined CSS file and save it to a folder. After that you can load and use this CSS file like you would any other CSS file.

//Name of the combined static CSS file
$css->setTargetPath('combined.css');

/*
* Combine the above three CSS stylesheets into a
* single stylesheet and save it as assets/css/combined.css
*/ $am = new Assetic\AssetManager(); $am->set("min", $css);
$writer = new Assetic\AssetWriter(FCPATH . 'assets/css/'); $writer->writeManagerAssets($am);