View.php 20 KB

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