alexandernst
alexandernst

Reputation: 15099

Changing widget assets path at runtime

I have a widget that uses assets. The asset look like this:

class publicHeaderNavbarAsset extends AssetBundle {
    public $sourcePath = '@app/components/@device';
    public $css = [
        'styles.css'
    ];
    public $js = [];
    public $depends = [];
}

I also have a (bootstrapped) component, defined like that:

class Aliases extends Component {
    public function init() {
        Yii::setAlias('@device', Utils::device());
    }
}

Utils::device() is a function that parses the UA of the device and returns mobile, tablet or desktop, depending on the device type.

The problem is that Yii2 doesn't seem to be converting @device to the value it has. I first thought that it could be my fault, but then I changed the sourcePath to:

public $sourcePath = '@app/components/@app';

just to see if that will trigger an error with a duplicated path (basepath/componenets/basepath), but it didn't.

Is there a way I can change the sourcePath of my asset at runtime? Or maybe make Yii2 parse all the aliases in sourcePath?

Upvotes: 0

Views: 68

Answers (1)

Mihai P.
Mihai P.

Reputation: 9367

Look at the getAlias function http://www.getyii.com/doc-2.0/api/yii-baseyii.html#getAlias()-detail It will basically not match your second alias in the string you have given it.

You can try setting

Yii::setAlias('@device', '@app/components/' . Utils::device()); 

and

public $sourcePath = '@device';

This should work as you should be able to set an alias based on another alias http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html#defining-aliases

Upvotes: 1

Related Questions