bcmcfc
bcmcfc

Reputation: 26765

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

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...

Upvotes: 6

Views: 2518

Answers (2)

exiang
exiang

Reputation: 559

I think a better way to enhance @bcmcfc function is by remain the default ordering while ensure those with priority works.

I modify the renderHead() function here.

public function renderHead(&$output)
{
    $cssFilesOrdered = array();
    $currentCssFiles = $this->cssFiles;
    //print_r($currentCssFiles);
    if (!empty($this->priority))
    {
        // sort priority array according to value (priority number)
        asort($this->priority);
        $tmp = array_values($this->priority);
        $startPriority = $tmp[0];
        # 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);
        $startCounter = $startPriority-count($currentCssFiles);
        foreach ($currentCssFiles as $path => $v)
        {
            if (!in_array($path, $cssFilesWithPrioritySet))
            {
                $this->priority[$path] = $startCounter++;
            }
        }

        asort($this->priority);
        foreach ($this->priority as $path => $id)
        {
            $cssFilesOrdered[$path] = $currentCssFiles[$path];
            unset($currentCssFiles[$path]);
        }
    }

    if (!empty($cssFilesOrdered)){
        $this->cssFiles = $cssFilesOrdered;
    }
    # add any remaining CSS files that didn't have an order specified
    $cssFilesOrdered += $currentCssFiles;
    parent::renderHead($output);
}

Upvotes: 0

bcmcfc
bcmcfc

Reputation: 26765

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;
            }
        }
    }

}

Upvotes: 5

Related Questions