What is the best way to register js code in yii2 view?
registerJs(
\'$(\"document\").ready(function(){ alert(\"hi\"); });\
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
registerJs(preg_replace('~^\s*|\s*$~ U', '', ob_get_clean()));
}
}
usage example (within view)
registerJs(preg_replace('~^\s*|\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 :)