Created
April 8, 2016 07:14
-
-
Save turboezh/1f970651dc795779495d03d907c2309e to your computer and use it in GitHub Desktop.
Yii2 JS script widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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