Search code examples
yii2bundleassetsdepends

Yii2 location from dependencies in custom asset


I have a path something like /actions/users/someaction in the frontend and I want to use the Bootstrap-Asset (located in /backend/web/assets/xxxxxx/) from the backend.

So I created an asset called "ActionAsset" with following content:

class ActionAsset extends AssetBundle
{
    public $basePath = '@backend';
    public $baseUrl = '@web/backend';
    public $css = [
        'css/external.css',
        'css/overwrite-bootstrap.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BackendBootstrapAsset',
    ];
}

The included css are just working fine, but the dependencies are always saved in /frontend/web/assets/. My question is (and I really searched for weeks) how to change this location to /backend/web/assets.


Solution

  • You need to define $sourcePath. Yii2 AssetManager will copy (or symlink) your assets in your current web/assets/ folder.

    From the docs

    sourcePath: specifies the root directory that contains the asset files in this bundle. This property should be set if the root directory is not Web accessible. Otherwise, you should set the basePath property and baseUrl, instead. Path aliases can be used here.

    So change your code to:

    class ActionAsset extends AssetBundle
    {
        public $sourcePath = '<path to your asste content>';
        public $css = [
            'css/external.css',
            'css/overwrite-bootstrap.css',
        ];
        public $js = [
        ];
        public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap\BackendBootstrapAsset',
        ];
    }
    

    Or: Just overwrite your asstetbundle in @frontend/asset and set $sourcePath property accordingly:

    class FrontendActionAsset extends ActionAsset
    {
        public $sourcePath = '<path to your asste content>'; //you don't need more
    }