Assets included on certain views

Is there a way to only include Assets based on certain views?

I know in Yii 2 I use to use registerJSFile() a lot etc.

But in Yii 2 we not have Asset Bundles, but these only seem to handle global includes of files.

I use have a structure like so …


Would be loaded on …

site/index controller/action

And …


Would be loaded on …

user/create controller/action

Is there any way to do this with Yii 2?

in your view you can add

use frontend\assets\SomeNewBundelAsset;


If you look in your app there will be an example called AppAssets in backend/assets and frontend/assets

You can also read about them here in the Yii2 docs.

Yes as skworden said but here is a bit more details for the beginners like me:

Add your files to the web directory, for example:



Create new asset bundle:

/assets/MyAsset.php and add your files to it, for example:


namespace frontend\assets;

use yii\web\AssetBundle;

class MyAsset extends AssetBundle


    public $basePath = '@webroot';

    public $baseUrl = '@web';

    public $css = [



    public $js = [



    public $depends = [

        'front\assets\AppAsset', // if you want your asset bundle to be requested after AppAsset



In your view views/site/myView.php Add:

use frontend\assets\MyAsset;


Any by this way you will have a specific assets for a specific view.

1 Like