What is the best way to register js code in yii2 view?
registerJs(
\'$(\"document\").ready(function(){ alert(\"hi\"); });\
Yii2, write code in views
<h2>Content</h2>
<?php
$script = <<< JS
alert("Hi");
JS;
$this->registerJs($script);
?>
<?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
I prefer use richardfan's widget:
use richardfan\widget\JSRegister;
<?php JSRegister::begin(['position' => static::POS_BEGIN]); ?>
<script>
alert('Hello world');
</script>
<?php JSRegister::end(); ?>
I have created a trivial widget that allows me to keep the code clean and allow proper parsing by the IDE.
common/widget/InlineScript.php
<?php namespace common\widgets;
/**
* Easily add JS to the end of the document.
*/
class InlineScript {
/**
* Open output buffer.
*/
public static function listen() {
ob_start();
}
/**
* Capture the output buffer and register the JS.
*
* @param yii\web\View $view The view that should register the JS.
*/
public static function capture($view) {
$view->registerJs(preg_replace('~^\s*<script.*>|</script>\s*$~ U', '', ob_get_clean()));
}
}
usage example (within view)
<?php ob_start(); ?>
<script>
alert('asd');
</script>
<?php $this->registerJs(preg_replace('~^\s*<script.*>|</script>\s*$~ U', '', ob_get_clean())) ?>
As you see, this does use output buffers, so one needs to be carefull about using this. If every listen()
isn't followed by exaclty one capture()
you might get into debugging nightmare :)