View.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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\base;
  8. use Yii;
  9. use yii\helpers\FileHelper;
  10. use yii\widgets\Block;
  11. use yii\widgets\ContentDecorator;
  12. use yii\widgets\FragmentCache;
  13. /**
  14. * View represents a view object in the MVC pattern.
  15. *
  16. * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
  17. *
  18. * @author Qiang Xue <[email protected]>
  19. * @since 2.0
  20. */
  21. class View extends Component
  22. {
  23. /**
  24. * @event Event an event that is triggered by [[beginPage()]].
  25. */
  26. const EVENT_BEGIN_PAGE = 'beginPage';
  27. /**
  28. * @event Event an event that is triggered by [[endPage()]].
  29. */
  30. const EVENT_END_PAGE = 'endPage';
  31. /**
  32. * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
  33. */
  34. const EVENT_BEFORE_RENDER = 'beforeRender';
  35. /**
  36. * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
  37. */
  38. const EVENT_AFTER_RENDER = 'afterRender';
  39. /**
  40. * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
  41. */
  42. public $context;
  43. /**
  44. * @var mixed custom parameters that are shared among view templates.
  45. */
  46. public $params = [];
  47. /**
  48. * @var array a list of available renderers indexed by their corresponding supported file extensions.
  49. * Each renderer may be a view renderer object or the configuration for creating the renderer object.
  50. * For example, the following configuration enables both Smarty and Twig view renderers:
  51. *
  52. * ~~~
  53. * [
  54. * 'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
  55. * 'twig' => ['class' => 'yii\twig\ViewRenderer'],
  56. * ]
  57. * ~~~
  58. *
  59. * If no renderer is available for the given view file, the view file will be treated as a normal PHP
  60. * and rendered via [[renderPhpFile()]].
  61. */
  62. public $renderers;
  63. /**
  64. * @var string the default view file extension. This will be appended to view file names if they don't have file extensions.
  65. */
  66. public $defaultExtension = 'php';
  67. /**
  68. * @var Theme|array the theme object or the configuration array for creating the theme object.
  69. * If not set, it means theming is not enabled.
  70. */
  71. public $theme;
  72. /**
  73. * @var array a list of named output blocks. The keys are the block names and the values
  74. * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]]
  75. * to capture small fragments of a view. They can be later accessed somewhere else
  76. * through this property.
  77. */
  78. public $blocks;
  79. /**
  80. * @var array a list of currently active fragment cache widgets. This property
  81. * is used internally to implement the content caching feature. Do not modify it directly.
  82. * @internal
  83. */
  84. public $cacheStack = [];
  85. /**
  86. * @var array a list of placeholders for embedding dynamic contents. This property
  87. * is used internally to implement the content caching feature. Do not modify it directly.
  88. * @internal
  89. */
  90. public $dynamicPlaceholders = [];
  91. /**
  92. * Initializes the view component.
  93. */
  94. public function init()
  95. {
  96. parent::init();
  97. if (is_array($this->theme)) {
  98. if (!isset($this->theme['class'])) {
  99. $this->theme['class'] = 'yii\base\Theme';
  100. }
  101. $this->theme = Yii::createObject($this->theme);
  102. }
  103. }
  104. /**
  105. * Renders a view.
  106. *
  107. * The view to be rendered can be specified in one of the following formats:
  108. *
  109. * - path alias (e.g. "@app/views/site/index");
  110. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  111. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  112. * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
  113. * The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
  114. * - resolving any other format will be performed via [[ViewContext::findViewFile()]].
  115. *
  116. * @param string $view the view name. Please refer to [[Controller::findViewFile()]]
  117. * and [[Widget::findViewFile()]] on how to specify this parameter.
  118. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  119. * @param object $context the context that the view should use for rendering the view. If null,
  120. * existing [[context]] will be used.
  121. * @return string the rendering result
  122. * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
  123. * @see renderFile()
  124. */
  125. public function render($view, $params = [], $context = null)
  126. {
  127. $viewFile = $this->findViewFile($view, $context);
  128. return $this->renderFile($viewFile, $params, $context);
  129. }
  130. /**
  131. * Finds the view file based on the given view name.
  132. * @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
  133. * on how to specify this parameter.
  134. * @param object $context the context that the view should be used to search the view file. If null,
  135. * existing [[context]] will be used.
  136. * @return string the view file path. Note that the file may not exist.
  137. * @throws InvalidCallException if [[context]] is required and invalid.
  138. */
  139. protected function findViewFile($view, $context = null)
  140. {
  141. if (strncmp($view, '@', 1) === 0) {
  142. // e.g. "@app/views/main"
  143. $file = Yii::getAlias($view);
  144. } elseif (strncmp($view, '//', 2) === 0) {
  145. // e.g. "//layouts/main"
  146. $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  147. } elseif (strncmp($view, '/', 1) === 0) {
  148. // e.g. "/site/index"
  149. if (Yii::$app->controller !== null) {
  150. $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  151. } else {
  152. throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
  153. }
  154. } else {
  155. // context required
  156. if ($context === null) {
  157. $context = $this->context;
  158. }
  159. if ($context instanceof ViewContextInterface) {
  160. $file = $context->findViewFile($view);
  161. } else {
  162. throw new InvalidCallException("Unable to locate view file for view '$view': no active view context.");
  163. }
  164. }
  165. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  166. return $file;
  167. }
  168. $path = $file . '.' . $this->defaultExtension;
  169. if ($this->defaultExtension !== 'php' && !is_file($path)) {
  170. $path = $file . '.php';
  171. }
  172. return $path;
  173. }
  174. /**
  175. * Renders a view file.
  176. *
  177. * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
  178. * as it is available.
  179. *
  180. * The method will call [[FileHelper::localize()]] to localize the view file.
  181. *
  182. * If [[renderer]] is enabled (not null), the method will use it to render the view file.
  183. * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
  184. * return it as a string.
  185. *
  186. * @param string $viewFile the view file. This can be either a file path or a path alias.
  187. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  188. * @param object $context the context that the view should use for rendering the view. If null,
  189. * existing [[context]] will be used.
  190. * @return string the rendering result
  191. * @throws InvalidParamException if the view file does not exist
  192. */
  193. public function renderFile($viewFile, $params = [], $context = null)
  194. {
  195. $viewFile = Yii::getAlias($viewFile);
  196. if ($this->theme !== null) {
  197. $viewFile = $this->theme->applyTo($viewFile);
  198. }
  199. if (is_file($viewFile)) {
  200. $viewFile = FileHelper::localize($viewFile);
  201. } else {
  202. throw new InvalidParamException("The view file does not exist: $viewFile");
  203. }
  204. $oldContext = $this->context;
  205. if ($context !== null) {
  206. $this->context = $context;
  207. }
  208. $output = '';
  209. if ($this->beforeRender($viewFile)) {
  210. Yii::trace("Rendering view file: $viewFile", __METHOD__);
  211. $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
  212. if (isset($this->renderers[$ext])) {
  213. if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
  214. $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
  215. }
  216. /** @var ViewRenderer $renderer */
  217. $renderer = $this->renderers[$ext];
  218. $output = $renderer->render($this, $viewFile, $params);
  219. } else {
  220. $output = $this->renderPhpFile($viewFile, $params);
  221. }
  222. $this->afterRender($viewFile, $output);
  223. }
  224. $this->context = $oldContext;
  225. return $output;
  226. }
  227. /**
  228. * This method is invoked right before [[renderFile()]] renders a view file.
  229. * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
  230. * If you override this method, make sure you call the parent implementation first.
  231. * @param string $viewFile the view file to be rendered
  232. * @return boolean whether to continue rendering the view file.
  233. */
  234. public function beforeRender($viewFile)
  235. {
  236. $event = new ViewEvent($viewFile);
  237. $this->trigger(self::EVENT_BEFORE_RENDER, $event);
  238. return $event->isValid;
  239. }
  240. /**
  241. * This method is invoked right after [[renderFile()]] renders a view file.
  242. * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
  243. * If you override this method, make sure you call the parent implementation first.
  244. * @param string $viewFile the view file to be rendered
  245. * @param string $output the rendering result of the view file. Updates to this parameter
  246. * will be passed back and returned by [[renderFile()]].
  247. */
  248. public function afterRender($viewFile, &$output)
  249. {
  250. if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
  251. $event = new ViewEvent($viewFile);
  252. $event->output = $output;
  253. $this->trigger(self::EVENT_AFTER_RENDER, $event);
  254. $output = $event->output;
  255. }
  256. }
  257. /**
  258. * Renders a view file as a PHP script.
  259. *
  260. * This method treats the view file as a PHP script and includes the file.
  261. * It extracts the given parameters and makes them available in the view file.
  262. * The method captures the output of the included view file and returns it as a string.
  263. *
  264. * This method should mainly be called by view renderer or [[renderFile()]].
  265. *
  266. * @param string $_file_ the view file.
  267. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  268. * @return string the rendering result
  269. */
  270. public function renderPhpFile($_file_, $_params_ = [])
  271. {
  272. ob_start();
  273. ob_implicit_flush(false);
  274. extract($_params_, EXTR_OVERWRITE);
  275. require($_file_);
  276. return ob_get_clean();
  277. }
  278. /**
  279. * Renders dynamic content returned by the given PHP statements.
  280. * This method is mainly used together with content caching (fragment caching and page caching)
  281. * when some portions of the content (called *dynamic content*) should not be cached.
  282. * The dynamic content must be returned by some PHP statements.
  283. * @param string $statements the PHP statements for generating the dynamic content.
  284. * @return string the placeholder of the dynamic content, or the dynamic content if there is no
  285. * active content cache currently.
  286. */
  287. public function renderDynamic($statements)
  288. {
  289. if (!empty($this->cacheStack)) {
  290. $n = count($this->dynamicPlaceholders);
  291. $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
  292. $this->addDynamicPlaceholder($placeholder, $statements);
  293. return $placeholder;
  294. } else {
  295. return $this->evaluateDynamicContent($statements);
  296. }
  297. }
  298. /**
  299. * Adds a placeholder for dynamic content.
  300. * This method is internally used.
  301. * @param string $placeholder the placeholder name
  302. * @param string $statements the PHP statements for generating the dynamic content
  303. */
  304. public function addDynamicPlaceholder($placeholder, $statements)
  305. {
  306. foreach ($this->cacheStack as $cache) {
  307. $cache->dynamicPlaceholders[$placeholder] = $statements;
  308. }
  309. $this->dynamicPlaceholders[$placeholder] = $statements;
  310. }
  311. /**
  312. * Evaluates the given PHP statements.
  313. * This method is mainly used internally to implement dynamic content feature.
  314. * @param string $statements the PHP statements to be evaluated.
  315. * @return mixed the return value of the PHP statements.
  316. */
  317. public function evaluateDynamicContent($statements)
  318. {
  319. return eval($statements);
  320. }
  321. /**
  322. * Begins recording a block.
  323. * This method is a shortcut to beginning [[Block]]
  324. * @param string $id the block ID.
  325. * @param boolean $renderInPlace whether to render the block content in place.
  326. * Defaults to false, meaning the captured block will not be displayed.
  327. * @return Block the Block widget instance
  328. */
  329. public function beginBlock($id, $renderInPlace = false)
  330. {
  331. return Block::begin([
  332. 'id' => $id,
  333. 'renderInPlace' => $renderInPlace,
  334. 'view' => $this,
  335. ]);
  336. }
  337. /**
  338. * Ends recording a block.
  339. */
  340. public function endBlock()
  341. {
  342. Block::end();
  343. }
  344. /**
  345. * Begins the rendering of content that is to be decorated by the specified view.
  346. * This method can be used to implement nested layout. For example, a layout can be embedded
  347. * in another layout file specified as '@app/views/layouts/base.php' like the following:
  348. *
  349. * ~~~
  350. * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
  351. * ...layout content here...
  352. * <?php $this->endContent(); ?>
  353. * ~~~
  354. *
  355. * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
  356. * This can be specified as either the view file path or path alias.
  357. * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
  358. * @return ContentDecorator the ContentDecorator widget instance
  359. * @see ContentDecorator
  360. */
  361. public function beginContent($viewFile, $params = [])
  362. {
  363. return ContentDecorator::begin([
  364. 'viewFile' => $viewFile,
  365. 'params' => $params,
  366. 'view' => $this,
  367. ]);
  368. }
  369. /**
  370. * Ends the rendering of content.
  371. */
  372. public function endContent()
  373. {
  374. ContentDecorator::end();
  375. }
  376. /**
  377. * Begins fragment caching.
  378. * This method will display cached content if it is available.
  379. * If not, it will start caching and would expect an [[endCache()]]
  380. * call to end the cache and save the content into cache.
  381. * A typical usage of fragment caching is as follows,
  382. *
  383. * ~~~
  384. * if ($this->beginCache($id)) {
  385. * // ...generate content here
  386. * $this->endCache();
  387. * }
  388. * ~~~
  389. *
  390. * @param string $id a unique ID identifying the fragment to be cached.
  391. * @param array $properties initial property values for [[FragmentCache]]
  392. * @return boolean whether you should generate the content for caching.
  393. * False if the cached version is available.
  394. */
  395. public function beginCache($id, $properties = [])
  396. {
  397. $properties['id'] = $id;
  398. $properties['view'] = $this;
  399. /** @var FragmentCache $cache */
  400. $cache = FragmentCache::begin($properties);
  401. if ($cache->getCachedContent() !== false) {
  402. $this->endCache();
  403. return false;
  404. } else {
  405. return true;
  406. }
  407. }
  408. /**
  409. * Ends fragment caching.
  410. */
  411. public function endCache()
  412. {
  413. FragmentCache::end();
  414. }
  415. /**
  416. * Marks the beginning of a page.
  417. */
  418. public function beginPage()
  419. {
  420. ob_start();
  421. ob_implicit_flush(false);
  422. $this->trigger(self::EVENT_BEGIN_PAGE);
  423. }
  424. /**
  425. * Marks the ending of a page.
  426. */
  427. public function endPage()
  428. {
  429. $this->trigger(self::EVENT_END_PAGE);
  430. ob_end_flush();
  431. }
  432. }