yii2 register js code in a view

前端 未结 4 2029
逝去的感伤
逝去的感伤 2021-02-19 08:52

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

1

registerJs(
    \'$(\"document\").ready(function(){ alert(\"hi\"); });\         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 09:44

    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 :)

提交回复
热议问题