How to keep a very tight control over the order of CSS files in Yii Framework


Tags: css,yii

Problem :

In Yii there are many different ways to get CSS into your pages.

The problem is, once you start using extensions, widgets, themes and the like, they all have their own stylesheets (fair enough) and the order in which the CSS gets processed and inserted into the HTML varies according to whether they were set in the controller, view or layout, or are using the Yii asset manager, or the Yii package manager.

Recently, our Yii project was altered to use packages registered in config/main.php, in this way:

'clientScript'=>array(
        'packages'=> array(
            'theme'=>array(
                'basePath'=>'yii.themes.default',
                'css'=>array('css/reset.css','css/main.css','css/form.css'),
                'js'=>array('js/lib.js'),
                'depends'=>array('jquery'),
            ),
...

This caused a CSS file to break as it was designed to override grid-view styles and it was now being included before the CGridView stylesheet.

The solution was to add these lines at the bottom of layouts/main.php:

$path = Yii::getPathOfAlias('yii.themes.default').'/css/style.css';
$cssFile = Yii::app()->getAssetManager()->publish($path);
Yii::app()->getClientScript()->registerCssFile($cssFile);

To me, this feels like a less than perfect solution, and I expect we may have problems in the future when we forget what we've done, or we have to do a similar thing with a different theme, or a different project entirely.

Is there a better way of managing the CSS effectively when it can be provided from so many different sources?

Edit:

I am considering extending CClientScript to provide an 'overrides' sort of option, in which you could specify an array of CSS files that the file you're registering should be included after. It feels like it could be a bit flaky though...



Solution :

I've come up with the following solution, using an approach similar to how z-index works. It's not perfect though by any stretch.

Stylesheets are set to have a priority of 0 by default, and you can set this using registerCss and registerCssFile, to a positive or negative integer. A negative integer will insert the file before the rest of the CSS, and a positive integer will send it to the end.

In config/main.php, set the clientScript to use the new class:

    'clientScript'=>array(
        'class' => 'components\ClientScript',
        ...

components/ClientScript.php:

I was playing around with the idea of specifying dependencies between the registered files instead of an integer based priority, but didn't follow it through. I've left that code in here for now in case anyone wants to take it on.

class ClientScript extends CClientScript
{

    protected $dependencies = array();
    protected $priority = array();

    public function renderHead(&$output)
    {
        $cssFilesOrdered = array();
        $currentCssFiles = $this->cssFiles;

        if (!empty($this->priority)){
            # assign 0 to anything without a specific priority
            # can't do this in the register method because not every CSS file that ends up here used it
            $cssFilesWithPrioritySet = array_keys($this->priority);
            foreach ($currentCssFiles as $path => $v){
                if (!in_array($path, $cssFilesWithPrioritySet)){
                    $this->priority[$path] = 0;
                }
            }

            asort($this->priority);
            foreach ($this->priority as $path => $id){
                $cssFilesOrdered[$path] = $currentCssFiles[$path];
                unset($currentCssFiles[$path]);
            }
            # add any remaining CSS files that didn't have an order specified
            $cssFilesOrdered += $currentCssFiles;
        }

        if (!empty($cssFilesOrdered)){
            $this->cssFiles = $cssFilesOrdered;
        }

        parent::renderHead($output);
    }

    public function registerCssFile($url, $media = '', $order = null)
    {
        $this->setOrder($url, $order);
        return parent::registerCssFile($url, $media);
    }

    public function registerCss($id, $css, $media = '', $order = null)
    {
        $this->setOrder($id, $order);
        return parent::registerCss($id, $css, $media);
    }

    private function setOrder($identifier, $order)
    {
        if (!is_null($order)){
            if (is_array($order)){
                $this->dependencies[$identifier] = $order;
            } elseif (is_numeric($order)){
                $this->priority[$identifier] = $order;
            }
        }
    }

}

    CSS Howto..

    How to align div blocks to be aligned in grid?

    How to detect when one or more JS/CSS library fail to load (e.g. CDN)?

    How to I get this element to span 100% of LI? [closed]

    How to change CSS when user scrolls past a certain div

    how to make this div margin to zero and more nature [closed]

    How to make border for UL if Li has style “float:left;”?

    how to set shadow for round image(css)

    How can I set all columns to be the same height? [duplicate]

    How to center links in header using CSS?

    How to disable correctly CSS3 transition property when needed

    Wordpress plugin: How to depend on other plugins?

    How to use html entities in CSS content property?

    How is a CSS “display: table-column” supposed to work?

    How to put text over img on hover - width and height are variable

    How do you achieve this backwards div effect? [closed]

    How to make text wrap when resizing in a inline div, without the div moving onto a new line first?

    How to set original image for animate background image in css

    CSS - how to code for a specific resolution

    How to use CSS filters in JavaScript?

    How to create four even and fluid css columns?

    How to make a list float to the right in CSS?

    how to achieve this effect with css html?

    How to implement fade in effect for CSS checkbox

    How to manipulate the CSS at runtime

    How to replace non-existing images with a default one in css?

    How to get these timestamps, which come after in the html, to float right on the same line

    How to css this little button next to