Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 registering JS files to a View

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/ ?

like image 871
David Avatar asked Dec 26 '14 11:12

David


2 Answers

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()]]); ?>
like image 107
xav Avatar answered Oct 21 '22 22:10

xav


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 = [
    ];
}
like image 23
Ilyas karim Avatar answered Oct 21 '22 23:10

Ilyas karim