Friday 11 November 2016

Yii2 include js file in view

Register your js file on given possion

$this->registerJsFile('path/to/file.js', ['position' => \yii\web\View::POS_END]);

The first argument is the actual JS code we want to insert into the page. The second argument determines where script should be inserted into the page. Possible values are:

    View::POS_HEAD for head section.

    View::POS_BEGIN for right after opening .

    View::POS_END for right before closing .

    View::POS_READY for executing code on document ready event.

This will register jQuery automatically. View::POS_LOAD for executing code on document load event. This will register jQuery automatically. The last argument is a unique script ID that is used to identify code block and replace existing one with the same ID instead of adding a new one. If you don't provide it, the JS code itself will be used as the ID.

An external script can be added like the following:

$this->registerJsFile('http://example.com/js/main.js', ['depends' => [\yii\web\JqueryAsset::className()]]);

The arguments for registerJsFile() are similar to those for registerCssFile(). In the above example, we register the main.js file with the dependency on JqueryAsset. This means the main.js file will be added AFTER jquery.js. Without this dependency specification, the relative order between main.js and jquery.js would be undefined.

Soruce: http://stackoverflow.com/questions/27656777/yii2-registering-js-files-to-a-view


No comments:

Post a Comment