-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJsBlock.php
55 lines (48 loc) · 1.31 KB
/
JsBlock.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace mootensai\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);
}
}