JsBlock.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2016-07-08 14:23
  7. */
  8. namespace common\widgets;
  9. use yii\web\View;
  10. use yii\widgets\Block;
  11. use yii\base\InvalidParamException;
  12. class JsBlock extends Block
  13. {
  14. /**
  15. * @var null
  16. */
  17. public $key = null;
  18. /**
  19. * @var int
  20. */
  21. public $pos = View::POS_END;
  22. /**
  23. * Ends recording a block.
  24. * This method stops output buffering and saves the rendering result as a named block in the view.
  25. */
  26. public function run()
  27. {
  28. $block = ob_get_clean();
  29. if ($this->renderInPlace) {
  30. throw new InvalidParamException("Not implemented yet ! ");
  31. }
  32. $block = trim($block);
  33. /*
  34. $jsBlockPattern = '|^<script[^>]*>(.+?)</script>$|is';
  35. if(preg_match($jsBlockPattern,$block)){
  36. $block = preg_replace ( $jsBlockPattern , '${1}' , $block );
  37. }
  38. */
  39. $jsBlockPattern = '|^<script[^>]*>(?P<block_content>.+?)</script>$|is';
  40. if (preg_match($jsBlockPattern, $block, $matches)) {
  41. $block = $matches['block_content'];
  42. }
  43. $this->view->registerJs($block, $this->pos, $this->key);
  44. }
  45. }