Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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