In order to use JavaScript with Yii2 framework, we have to register scripts with yii\web\view
object. Yii2 provides two methods for it
- registerJs() for inline scripts
- registerJsFile() for external script files.
registerJs() for inline scripts
Here is an example to register an inline script.
$script = "function test() {console.log('a meesage logged in console.'); alert('Hello World');}"; $this->registerJs($script, View::POS_END, 'my-options');
Where:
- First argument is the script content itself
- Second argument determines the place in the page where the script should be inserted, e.g. Head, Begin, End, Load etc.
- And the last argument is used to uniquely identify the code block
Here is our test html to call this javascript test()
function.
&input type="button" value="Click Me" onclick="test();"\>
registerJsFile() for external script files.
An external JavaScript file can be added with the method registerJsFile()
.
$this->registerJsFile('http://localhost/yiidemo/js/main.js');
Registering with Asset Bundles
Another way to use JavaScript files in Yii2 framework is by registering it in asset bundles, and is preferred to use asset bundles instead of using JavaScript code/files directly You can use the following syntax to register current view for asset bundle.
\yiidemo\assets\AppAsset::register($this);
With the following javascipt configuration block in AppAsset.php
public $js = [ '../assets/js/myjs1.js', ];
References:
http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html
Nice post. I was checking continuously this blog and I am impressed! Very helpful information specially the last part :) I care for such info a lot. I was looking for this certain info for a long time. Thank you
ReplyDeleteYii Framework Development Company – Nintriva