yii2 register js code in a view

前端 未结 4 2028
逝去的感伤
逝去的感伤 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:30

    Yii2, write code in views

    <h2>Content</h2>
    <?php
    $script = <<< JS
        alert("Hi");
    JS;
    $this->registerJs($script);
    ?>
    
    0 讨论(0)
  • 2021-02-19 09:36
    <?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

    0 讨论(0)
  • 2021-02-19 09:39

    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(); ?>
    
    0 讨论(0)
  • 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

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

    0 讨论(0)
提交回复
热议问题