'yii2 register js code in a view

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

1

<?php
    $this->registerJs(
    '$("document").ready(function(){ alert("hi"); });'
    );
  ?>

2

<?php 
     $this->registerJs('alert("hi");', View::POS_READY);
?>

3

<?php 
  $script = "function test() { alert('hi');}";    
  $this->registerJs($script, View::POS_END, 'my-options'); 
?>


Solution 1:[1]

Yii2, write code in views

<h2>Content</h2>
<?php
$script = <<< JS
    alert("Hi");
JS;
$this->registerJs($script);
?>

Solution 2:[2]

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

Solution 3:[3]

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(); ?>

Solution 4:[4]

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

Solution 5:[5]

Multiple ways to do this Way 1:

$script = "
                                $('.summary').append('<div class=\'pull-right\'><button class=\'btn btn-xs\' style=\'background:#ffb3b3;border-color:#ffb3b3;pointer-events:none;height:15px;width:15px\'></button> No BOM Available</div>');
                                ";
                        $this->registerJs($script);

Way 2:

 $js = <<< 'SCRIPT'
    $(document).on('ready pjax:success', function(){
        $('.select-on-check-all').change(function () {
            if ($('.select-on-check-all').is(":checked")) {
                $('#myTable tr').find("input[type='checkbox']:checked").each(function () {
                    keysArr.push($(this).val());
                });
            } else {
                $('#myTable tr').find("input[type='checkbox']:not(:checked)").each(function () {
                    var index = keysArr.indexOf($(this).val());
                    if (index != -1) {
                        keysArr.splice(index, 1);
                    }
                });
            }

            sessionStorage.setItem("keysArr", keysArr);
        });
    });
SCRIPT;
        $this->registerJs($js, \yii\web\View::POS_READY);

I hope this helps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivan Pirus
Solution 2 Nick Tsai
Solution 3 Leonardo Sapuy
Solution 4 Sabo
Solution 5 Aditya