Yii 2.0: yii2-js-register

Yii2 widget to register JS into view
3 followers

yii2-js-register

Yii2 widget to register JS into view

Get the full code from Github

Why do I need this?

How to register JS script into view in Yii2?

In Yii2, the way to register JS script into view is using \yii\web\View::registerJS(),

For example, if you want to initialize a jQuery plugin, you do:

// in view file
 
<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Hello World!</p>
      </div>
    </div>
  </div>
</div>
 
<?php
$this->registerJS('$(".modal").modal({backdrop:"static",keyboard:"false"})');
?>

Obviously, this is a very bad way because:

  1. Hard to read for human
  2. Hard to read for you editor (Means no syntax coloring for the JS code)
  3. You have to handle the single / double quote

This widget help you register JS script in Yii just as you write script block directly into HTML!

Getting Started

Installing

Install with Composer:

composer require richardfan1126/yii2-js-register "*"

or

php composer.phar require richardfan1126/yii2-js-register "*"

or add

"richardfan1126/yii2-js-register":"*"

to the require section of your composer.json file.

How to use

In your view file, wrap your JS script with <script> tag, and wrap all the things with this widget.

example:

// in view file
 
use richardfan\widget\JSRegister;
 
<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>Hello World!</p>
      </div>
    </div>
  </div>
</div>
 
<?php JSRegister::begin(); ?>
<script>
    $(".modal").modal({
        backdrop:"static",
        keyboard:"false"
    });
</script>
<?php JSRegister::end(); ?>

IMPORTANT Remember not to add anything out of the <script> block.

Configurations

There are 2 configurations for this widget, which are the parameters passed into \yii\web\View::registerJS() method. example:

<?php JSRegister::begin([
    'key' => 'bootstrap-modal',
    'position' => \yii\web\View::POS_READY
]); ?>
<script>
    // JS script
</script>
<?php JSRegister::end(); ?>
  • key (optional)The key that identifies the JS code block. If null, it will use $js as the key. If two JS code blocks are registered with the same key, the latter will overwrite the former. Default to null
  • position (optional) The position at which the JS script tag should be inserted in a page. Default to \yii\web\View::POS_READY

Total 1 comment

#19902 report it
yiqing95 at 2016/07/03 10:34am
oh this tech have been written long time ago

you can refer here: embedded javascript block in your view with IDE checking or intellisense

and the same as css:


 <?php
/**
 * User: yiqing
 * Date: 2014/12/15
 * Time: 0:21
 */

namespace year\widgets;


use yii\widgets\Block;

class CssBlock extends Block
{

    /**
     * @var null
     */
    public $key = null;
    /**
     * @var array $options the HTML attributes for the style tag.
     */
    public $options = [];

    /**
     * Ends recording a block.
     * This method stops output buffering and saves the rendering result as a named block in the view.
     */
    public function run()
    {
        $block = ob_get_clean();
        if ($this->renderInPlace) {
            throw new \Exception("not implemented yet ! ");
            // echo $block;
        }
        // $block = trim($block) ;
        $block = static::unwrapStyleTag($block);

        $this->view->registerCss($block, $this->options, $this->key);
    }

    /**
     * @param $cssBlock
     * @return string
     */
    public static function unwrapStyleTag($cssBlock)
    {
        $block = trim($cssBlock);
        /*
        $jsBlockPattern  = '|^<script[^>]*>(.+?)</script>$|is';
        if(preg_match($jsBlockPattern,$block)){
            $block =  preg_replace ( $jsBlockPattern , '${1}'  , $block );
        }
        */
        $cssBlockPattern = '|^<style[^>]*>(?P<block_content>.+?)</style>$|is';
        if (preg_match($cssBlockPattern, $block, $matches)) {
            $block = $matches['block_content'];
        }
        return $block;
    }
} 

Leave a comment

Please to leave your comment.

Create extension
Downloads
No downloadable files yet