ContentDecorator.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\InvalidConfigException;
  9. use yii\base\Widget;
  10. /**
  11. * ContentDecorator records all output between [[begin()]] and [[end()]] calls, passes it to the given view file
  12. * as `$content` and then echoes rendering result.
  13. *
  14. * ```php
  15. * <?php ContentDecorator::begin([
  16. * 'viewFile' => '@app/views/layouts/base.php',
  17. * 'params' => [],
  18. * 'view' => $this,
  19. * ]) ?>
  20. *
  21. * some content here
  22. *
  23. * <?php ContentDecorator::end() ?>
  24. * ```
  25. *
  26. * There are [[\yii\base\View::beginContent()]] and [[\yii\base\View::endContent()]] wrapper methods in the
  27. * [[\yii\base\View]] component to make syntax more friendly. In the view these could be used as follows:
  28. *
  29. * ```php
  30. * <?php $this->beginContent('@app/views/layouts/base.php') ?>
  31. *
  32. * some content here
  33. *
  34. * <?php $this->endContent() ?>
  35. * ```
  36. *
  37. * @author Qiang Xue <qiang.xue@gmail.com>
  38. * @since 2.0
  39. */
  40. class ContentDecorator extends Widget
  41. {
  42. /**
  43. * @var string the view file that will be used to decorate the content enclosed by this widget.
  44. * This can be specified as either the view file path or [path alias](guide:concept-aliases).
  45. */
  46. public $viewFile;
  47. /**
  48. * @var array the parameters (name => value) to be extracted and made available in the decorative view.
  49. */
  50. public $params = [];
  51. /**
  52. * Starts recording a clip.
  53. */
  54. public function init()
  55. {
  56. parent::init();
  57. if ($this->viewFile === null) {
  58. throw new InvalidConfigException('ContentDecorator::viewFile must be set.');
  59. }
  60. ob_start();
  61. ob_implicit_flush(false);
  62. }
  63. /**
  64. * Ends recording a clip.
  65. * This method stops output buffering and saves the rendering result as a named clip in the controller.
  66. */
  67. public function run()
  68. {
  69. $params = $this->params;
  70. $params['content'] = ob_get_clean();
  71. // render under the existing context
  72. echo $this->view->renderFile($this->viewFile, $params);
  73. }
  74. }