Yii Asset manager - css with image url

2019-04-28 15:58发布

问题:

I am using the following code to publish my css file to assets.

Yii::app()->clientScript->registerCssFile( Yii::app()->assetManager->publish( Yii::getPathOfAlias('application').'/../css/combo-autocomplete.css' ));

It registers the css successfully and styles are working fine, but the following css class using a image.

.ui-icon {
   background-image: url(../images/down-arrow.png); 
}

is not loading, it is referred to path inside assets folder. It is looking for the image inside

root/assets/images/

Is there any way to redirect the image url in the css to the original path, because i am not registering my images as assets as of now.

root/images

回答1:

Yii's asset manager is designed to let you package components such as UI widgets in a self-contained manner (the alternative being to manually distribute various files in different places inside your application directory structure). So if it makes sense to publish anything as an asset from your component, it makes sense to publish everything as an asset.

In that case, you should structure your component e.g. as

component/
    assets/
        css/
        images/
        js/

Then, publish the whole assets/ directory using Yii's asset manager instead of publishing files one by one. If you do this, they will end up being published in a manner like

assets/
    random_hash/
        css/
        images/

Your CSS can then simply refer to images with url(../images/image.jpg) without needing to know the value of random_hash.