Block.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use yii\base\Widget;
  9. /**
  10. * Block records all output between [[begin()]] and [[end()]] calls and stores it in [[\yii\base\View::$blocks]].
  11. * for later use.
  12. *
  13. * [[\yii\base\View]] component contains two methods [[\yii\base\View::beginBlock()]] and [[\yii\base\View::endBlock()]].
  14. * The general idea is that you're defining block default in a view or layout:
  15. *
  16. * ```php
  17. * <?php $this->beginBlock('messages', true) ?>
  18. * Nothing.
  19. * <?php $this->endBlock() ?>
  20. * ```
  21. *
  22. * And then overriding default in sub-views:
  23. *
  24. * ```php
  25. * <?php $this->beginBlock('username') ?>
  26. * Umm... hello?
  27. * <?php $this->endBlock() ?>
  28. * ```
  29. *
  30. * Second parameter defines if block content should be outputted which is desired when rendering its content but isn't
  31. * desired when redefining it in subviews.
  32. *
  33. * @author Qiang Xue <qiang.xue@gmail.com>
  34. * @since 2.0
  35. */
  36. class Block extends Widget
  37. {
  38. /**
  39. * @var bool whether to render the block content in place. Defaults to false,
  40. * meaning the captured block content will not be displayed.
  41. */
  42. public $renderInPlace = false;
  43. /**
  44. * Starts recording a block.
  45. */
  46. public function init()
  47. {
  48. parent::init();
  49. ob_start();
  50. ob_implicit_flush(false);
  51. }
  52. /**
  53. * Ends recording a block.
  54. * This method stops output buffering and saves the rendering result as a named block in the view.
  55. */
  56. public function run()
  57. {
  58. $block = ob_get_clean();
  59. if ($this->renderInPlace) {
  60. echo $block;
  61. }
  62. $this->view->blocks[$this->getId()] = $block;
  63. }
  64. }