I have A.php view file in /views/A/
folder.
And I have A.js js file in /views/A/
folder
Please help me register js file in view file.
As I understand I must write
$this->registerJsFile('path/to/file.js');
in view file.
But (Question A) I get method registerJsFile is not found in a class
message from PHPStorm.
Also (Question B) what should I write in path considering both files are in the same folder /views/A/
?
This is not elegant, but working if you need to have your js file registered after jquery (as seen in the Yii2 doc)
<?php $this->registerJsFile(Yii::$app->request->baseUrl.'/js/youFile.js',['depends' => [\yii\web\JqueryAsset::className()]]); ?>
If you register a js file by:
$this->registerJsFile("@web/js/all.js");
This will work but you will not be able to use jQuery. Because this file all.js
is loaded before jQuery. To load after jQuery we make it depend it on 'yii\web\YiiAsset'
or on \yii\web\JqueryAsset
. So it will be loaded after jQuery.js
. Example:
$this->registerJsFile("@web/js/all.js",[
'depends' => [
\yii\web\JqueryAsset::className()
]
]);
So What is difference between \yii\web\JqueryAsset
and \yii\web\YiiAsset
?
In jQueryAsset
the js file will load after jQuery.js
and in YiiAsset
the js file will load after yii.js
file.
If you want to create your own custom Asset Bundle:
<?php
namespace frontend\components;
use yii;
use yii\web\AssetBundle;
class CustomAssets extends AssetBundle
{
public $css = [
"path/to/css/file.css"
];
public $js = [
"path/to/js/file.js"
];
public $depends = [
];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With