選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

498 行
18KB

  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 InvalidParamException if the view cannot be resolved or the view file does not exist.
  136. * @see renderFile()
  137. */
  138. public function render($view, $params = [], $context = null)
  139. {
  140. $viewFile = $this->findViewFile($view, $context);
  141. return $this->renderFile($viewFile, $params, $context);
  142. }
  143. /**
  144. * Finds the view file based on the given view name.
  145. * @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
  146. * on how to specify this parameter.
  147. * @param object $context the context to be assigned to the view and can later be accessed via [[context]]
  148. * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
  149. * the view file corresponding to a relative view name.
  150. * @return string the view file path. Note that the file may not exist.
  151. * @throws InvalidCallException if a relative view name is given while there is no active context to
  152. * determine the corresponding view file.
  153. */
  154. protected function findViewFile($view, $context = null)
  155. {
  156. if (strncmp($view, '@', 1) === 0) {
  157. // e.g. "@app/views/main"
  158. $file = Yii::getAlias($view);
  159. } elseif (strncmp($view, '//', 2) === 0) {
  160. // e.g. "//layouts/main"
  161. $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  162. } elseif (strncmp($view, '/', 1) === 0) {
  163. // e.g. "/site/index"
  164. if (Yii::$app->controller !== null) {
  165. $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  166. } else {
  167. throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
  168. }
  169. } elseif ($context instanceof ViewContextInterface) {
  170. $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
  171. } elseif (($currentViewFile = $this->getViewFile()) !== false) {
  172. $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
  173. } else {
  174. throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
  175. }
  176. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  177. return $file;
  178. }
  179. $path = $file . '.' . $this->defaultExtension;
  180. if ($this->defaultExtension !== 'php' && !is_file($path)) {
  181. $path = $file . '.php';
  182. }
  183. return $path;
  184. }
  185. /**
  186. * Renders a view file.
  187. *
  188. * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
  189. * as it is available.
  190. *
  191. * The method will call [[FileHelper::localize()]] to localize the view file.
  192. *
  193. * If [[renderers|renderer]] is enabled (not null), the method will use it to render the view file.
  194. * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
  195. * return it as a string.
  196. *
  197. * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
  198. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  199. * @param object $context the context that the view should use for rendering the view. If null,
  200. * existing [[context]] will be used.
  201. * @return string the rendering result
  202. * @throws InvalidParamException if the view file does not exist
  203. */
  204. public function renderFile($viewFile, $params = [], $context = null)
  205. {
  206. $viewFile = Yii::getAlias($viewFile);
  207. if ($this->theme !== null) {
  208. $viewFile = $this->theme->applyTo($viewFile);
  209. }
  210. if (is_file($viewFile)) {
  211. $viewFile = FileHelper::localize($viewFile);
  212. } else {
  213. throw new InvalidParamException("The view file does not exist: $viewFile");
  214. }
  215. $oldContext = $this->context;
  216. if ($context !== null) {
  217. $this->context = $context;
  218. }
  219. $output = '';
  220. $this->_viewFiles[] = $viewFile;
  221. if ($this->beforeRender($viewFile, $params)) {
  222. Yii::trace("Rendering view file: $viewFile", __METHOD__);
  223. $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
  224. if (isset($this->renderers[$ext])) {
  225. if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
  226. $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
  227. }
  228. /* @var $renderer ViewRenderer */
  229. $renderer = $this->renderers[$ext];
  230. $output = $renderer->render($this, $viewFile, $params);
  231. } else {
  232. $output = $this->renderPhpFile($viewFile, $params);
  233. }
  234. $this->afterRender($viewFile, $params, $output);
  235. }
  236. array_pop($this->_viewFiles);
  237. $this->context = $oldContext;
  238. return $output;
  239. }
  240. /**
  241. * @return string|boolean the view file currently being rendered. False if no view file is being rendered.
  242. */
  243. public function getViewFile()
  244. {
  245. return end($this->_viewFiles);
  246. }
  247. /**
  248. * This method is invoked right before [[renderFile()]] renders a view file.
  249. * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
  250. * If you override this method, make sure you call the parent implementation first.
  251. * @param string $viewFile the view file to be rendered.
  252. * @param array $params the parameter array passed to the [[render()]] method.
  253. * @return boolean whether to continue rendering the view file.
  254. */
  255. public function beforeRender($viewFile, $params)
  256. {
  257. $event = new ViewEvent([
  258. 'viewFile' => $viewFile,
  259. 'params' => $params,
  260. ]);
  261. $this->trigger(self::EVENT_BEFORE_RENDER, $event);
  262. return $event->isValid;
  263. }
  264. /**
  265. * This method is invoked right after [[renderFile()]] renders a view file.
  266. * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
  267. * If you override this method, make sure you call the parent implementation first.
  268. * @param string $viewFile the view file being rendered.
  269. * @param array $params the parameter array passed to the [[render()]] method.
  270. * @param string $output the rendering result of the view file. Updates to this parameter
  271. * will be passed back and returned by [[renderFile()]].
  272. */
  273. public function afterRender($viewFile, $params, &$output)
  274. {
  275. if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
  276. $event = new ViewEvent([
  277. 'viewFile' => $viewFile,
  278. 'params' => $params,
  279. 'output' => $output,
  280. ]);
  281. $this->trigger(self::EVENT_AFTER_RENDER, $event);
  282. $output = $event->output;
  283. }
  284. }
  285. /**
  286. * Renders a view file as a PHP script.
  287. *
  288. * This method treats the view file as a PHP script and includes the file.
  289. * It extracts the given parameters and makes them available in the view file.
  290. * The method captures the output of the included view file and returns it as a string.
  291. *
  292. * This method should mainly be called by view renderer or [[renderFile()]].
  293. *
  294. * @param string $_file_ the view file.
  295. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  296. * @return string the rendering result
  297. */
  298. public function renderPhpFile($_file_, $_params_ = [])
  299. {
  300. ob_start();
  301. ob_implicit_flush(false);
  302. extract($_params_, EXTR_OVERWRITE);
  303. require($_file_);
  304. return ob_get_clean();
  305. }
  306. /**
  307. * Renders dynamic content returned by the given PHP statements.
  308. * This method is mainly used together with content caching (fragment caching and page caching)
  309. * when some portions of the content (called *dynamic content*) should not be cached.
  310. * The dynamic content must be returned by some PHP statements.
  311. * @param string $statements the PHP statements for generating the dynamic content.
  312. * @return string the placeholder of the dynamic content, or the dynamic content if there is no
  313. * active content cache currently.
  314. */
  315. public function renderDynamic($statements)
  316. {
  317. if (!empty($this->cacheStack)) {
  318. $n = count($this->dynamicPlaceholders);
  319. $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
  320. $this->addDynamicPlaceholder($placeholder, $statements);
  321. return $placeholder;
  322. } else {
  323. return $this->evaluateDynamicContent($statements);
  324. }
  325. }
  326. /**
  327. * Adds a placeholder for dynamic content.
  328. * This method is internally used.
  329. * @param string $placeholder the placeholder name
  330. * @param string $statements the PHP statements for generating the dynamic content
  331. */
  332. public function addDynamicPlaceholder($placeholder, $statements)
  333. {
  334. foreach ($this->cacheStack as $cache) {
  335. $cache->dynamicPlaceholders[$placeholder] = $statements;
  336. }
  337. $this->dynamicPlaceholders[$placeholder] = $statements;
  338. }
  339. /**
  340. * Evaluates the given PHP statements.
  341. * This method is mainly used internally to implement dynamic content feature.
  342. * @param string $statements the PHP statements to be evaluated.
  343. * @return mixed the return value of the PHP statements.
  344. */
  345. public function evaluateDynamicContent($statements)
  346. {
  347. return eval($statements);
  348. }
  349. /**
  350. * Begins recording a block.
  351. * This method is a shortcut to beginning [[Block]]
  352. * @param string $id the block ID.
  353. * @param boolean $renderInPlace whether to render the block content in place.
  354. * Defaults to false, meaning the captured block will not be displayed.
  355. * @return Block the Block widget instance
  356. */
  357. public function beginBlock($id, $renderInPlace = false)
  358. {
  359. return Block::begin([
  360. 'id' => $id,
  361. 'renderInPlace' => $renderInPlace,
  362. 'view' => $this,
  363. ]);
  364. }
  365. /**
  366. * Ends recording a block.
  367. */
  368. public function endBlock()
  369. {
  370. Block::end();
  371. }
  372. /**
  373. * Begins the rendering of content that is to be decorated by the specified view.
  374. * This method can be used to implement nested layout. For example, a layout can be embedded
  375. * in another layout file specified as '@app/views/layouts/base.php' like the following:
  376. *
  377. * ```php
  378. * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
  379. * //...layout content here...
  380. * <?php $this->endContent(); ?>
  381. * ```
  382. *
  383. * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
  384. * This can be specified as either the view file path or path alias.
  385. * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
  386. * @return ContentDecorator the ContentDecorator widget instance
  387. * @see ContentDecorator
  388. */
  389. public function beginContent($viewFile, $params = [])
  390. {
  391. return ContentDecorator::begin([
  392. 'viewFile' => $viewFile,
  393. 'params' => $params,
  394. 'view' => $this,
  395. ]);
  396. }
  397. /**
  398. * Ends the rendering of content.
  399. */
  400. public function endContent()
  401. {
  402. ContentDecorator::end();
  403. }
  404. /**
  405. * Begins fragment caching.
  406. * This method will display cached content if it is available.
  407. * If not, it will start caching and would expect an [[endCache()]]
  408. * call to end the cache and save the content into cache.
  409. * A typical usage of fragment caching is as follows,
  410. *
  411. * ```php
  412. * if ($this->beginCache($id)) {
  413. * // ...generate content here
  414. * $this->endCache();
  415. * }
  416. * ```
  417. *
  418. * @param string $id a unique ID identifying the fragment to be cached.
  419. * @param array $properties initial property values for [[FragmentCache]]
  420. * @return boolean whether you should generate the content for caching.
  421. * False if the cached version is available.
  422. */
  423. public function beginCache($id, $properties = [])
  424. {
  425. $properties['id'] = $id;
  426. $properties['view'] = $this;
  427. /* @var $cache FragmentCache */
  428. $cache = FragmentCache::begin($properties);
  429. if ($cache->getCachedContent() !== false) {
  430. $this->endCache();
  431. return false;
  432. } else {
  433. return true;
  434. }
  435. }
  436. /**
  437. * Ends fragment caching.
  438. */
  439. public function endCache()
  440. {
  441. FragmentCache::end();
  442. }
  443. /**
  444. * Marks the beginning of a page.
  445. */
  446. public function beginPage()
  447. {
  448. ob_start();
  449. ob_implicit_flush(false);
  450. $this->trigger(self::EVENT_BEGIN_PAGE);
  451. }
  452. /**
  453. * Marks the ending of a page.
  454. */
  455. public function endPage()
  456. {
  457. $this->trigger(self::EVENT_END_PAGE);
  458. ob_end_flush();
  459. }
  460. }