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 …
js/site/index.js
Would be loaded on …
site/index controller/action
And …
js/user/create.js
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;
SomeNewBundelAsset::register($this);
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:
/web/css/my.css
/web/js/my.js
Create new asset bundle:
/assets/MyAsset.php and add your files to it, for example:
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
class MyAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/my.css',
];
public $js = [
'js/my.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;
MyAsset::register($this);
Any by this way you will have a specific assets for a specific view.
1 Like