View.php 19 KB

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