Inline js
Во view можно подключить произвольный javascript код:
| |
| $var = 123; |
| |
| $script = <<< JS |
| function foo() { |
| return $var; |
| } |
| JS; |
| |
| $this->registerJs($script, yii\web\View::POS_READY); |
получим сразу перед закрытием body:
| |
| <script type="text/javascript"> |
| jQuery(document).ready(function () { |
| function foo() { |
| return 123; |
| } |
| });</script> |
другие варианты места подключения скрипта: (
документация)
- POS_HEAD: перед тегом </head>
- POS_BEGIN: после тэга <body>
- POS_END: перед тэгом </body>
- POS_LOAD: оборачивается в jQuery(window).load(). Note that by using this position, the method will automatically register the jQuery js file.
- POS_READY: оборачивается вjQuery(document).ready(). This is the default value. Note that by using this position, the method will automatically register the jQuery js file.
js-файл
$this->registerJsFile('url/to/file.js', ['position' => yii\web\View::POS_END]);
источник