Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 register js code in a view

Tags:

yii2

What is the best way to register js code in yii2 view?

1

<?php
    $this->registerJs(
    '$("document").ready(function(){ alert("hi"); });'
    );
  ?>

2

<?php 
     $this->registerJs('alert("hi");', View::POS_READY);
?>

3

<?php 
  $script = "function test() { alert('hi');}";    
  $this->registerJs($script, View::POS_END, 'my-options'); 
?>
like image 625
Muhammad Shahzad Avatar asked Apr 15 '16 06:04

Muhammad Shahzad


2 Answers

Yii2, write code in views

<h2>Content</h2>
<?php
$script = <<< JS
    alert("Hi");
JS;
$this->registerJs($script);
?>
like image 138
Ivan Pirus Avatar answered Sep 19 '22 17:09

Ivan Pirus


<?php 
$this->registerJs( <<< EOT_JS_CODE

  // JS code here

EOT_JS_CODE
);
?>

So you have not to escape js code

https://www.yiiframework.com/doc/guide/2.0/en/output-client-scripts

like image 43
Fabrizio Caldarelli Avatar answered Sep 23 '22 17:09

Fabrizio Caldarelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!