Skip to content

Instantly share code, notes, and snippets.

@mdmunir
Last active August 29, 2015 14:14
Show Gist options
  • Save mdmunir/b4e1ddb53d7025891275 to your computer and use it in GitHub Desktop.
Save mdmunir/b4e1ddb53d7025891275 to your computer and use it in GitHub Desktop.
Embedd Javascript Block Eith IDE Checking
<?php
namespace app\components;
use yii\web\View;
/**
* JsBlock
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class JsBlock extends \yii\base\Widget
{
public $key;
public $pos = View::POS_READY;
public $viewFile;
public $viewParams = [];
/**
* Starts recording a block.
*/
public function init()
{
if ($this->viewFile === null) {
ob_start();
ob_implicit_flush(false);
}
}
/**
* Ends recording a block.
* This method stops output buffering and saves the rendering result as a named block in the view.
*/
public function run()
{
if ($this->viewFile === null) {
$block = ob_get_clean();
} else {
$block = $this->view->render($this->viewFile, $this->viewParams);
}
$block = trim($block);
/**
* Thanks to yiqing
* http://www.yiiframework.com/wiki/752/embedded-javascript-block-in-your-view-with-ide-checking-or-intellisense/
*/
$jsBlockPattern = '|^<script[^>]*>(?P<block_content>.+?)</script>$|is';
if (preg_match($jsBlockPattern, $block, $matches)) {
$block = $matches['block_content'];
}
$this->view->registerJs($block, $this->pos, $this->key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment