Skip to content

Instantly share code, notes, and snippets.

@turboezh
Created April 8, 2016 07:14
Show Gist options
  • Save turboezh/1f970651dc795779495d03d907c2309e to your computer and use it in GitHub Desktop.
Save turboezh/1f970651dc795779495d03d907c2309e to your computer and use it in GitHub Desktop.
Yii2 JS script widget
<?php
namespace app\widgets;
use yii\base\Widget;
use yii\web\View;
/**
* Register JS script.
*
* Example:
*
* <?php JS::begin() ?>
* <script type="text/javascript">
* var SomeJsCode = 'FooBar';
* </script>
* <?php JS::end() ?>
*/
class JS extends Widget
{
/** @var int {@see yii\web\View::registerJs()} */
public $position = View::POS_READY;
/** @var string {@see yii\web\View::registerJs()} */
public $key;
public function init()
{
parent::init();
ob_start();
}
public function run()
{
$content = ob_get_clean();
$content = trim($this->stripScriptTag($content));
$this->getView()->registerJs($content, $this->position, $this->key);
}
private function stripScriptTag($content)
{
$content = preg_replace('#<script([^>]*)>#is', '', $content);
$content = preg_replace('#</script>#is', '', $content);
return $content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment