View.php 15.4 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\helpers\FileHelper;
12 13 14
use yii\widgets\Block;
use yii\widgets\ContentDecorator;
use yii\widgets\FragmentCache;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17
 * View represents a view object in the MVC pattern.
Qiang Xue committed
18
 *
Qiang Xue committed
19
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
Qiang Xue committed
20
 *
21 22 23
 * @property string|boolean $viewFile The view file currently being rendered. False if no view file is being
 * rendered. This property is read-only.
 *
Qiang Xue committed
24 25 26 27 28
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
29
	/**
Qiang Xue committed
30
	 * @event Event an event that is triggered by [[beginPage()]].
31 32 33
	 */
	const EVENT_BEGIN_PAGE = 'beginPage';
	/**
Qiang Xue committed
34
	 * @event Event an event that is triggered by [[endPage()]].
35 36
	 */
	const EVENT_END_PAGE = 'endPage';
37
	/**
38
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
39 40 41
	 */
	const EVENT_BEFORE_RENDER = 'beforeRender';
	/**
42
	 * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
43 44 45
	 */
	const EVENT_AFTER_RENDER = 'afterRender';

46
	/**
47
	 * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
48 49
	 */
	public $context;
Qiang Xue committed
50
	/**
Qiang Xue committed
51
	 * @var mixed custom parameters that are shared among view templates.
Qiang Xue committed
52
	 */
Alexander Makarov committed
53
	public $params = [];
Qiang Xue committed
54
	/**
Qiang Xue committed
55 56
	 * @var array a list of available renderers indexed by their corresponding supported file extensions.
	 * Each renderer may be a view renderer object or the configuration for creating the renderer object.
57 58 59
	 * For example, the following configuration enables both Smarty and Twig view renderers:
	 *
	 * ~~~
Alexander Makarov committed
60 61 62 63
	 * [
	 *     'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
	 *     'twig' => ['class' => 'yii\twig\ViewRenderer'],
	 * ]
64
	 * ~~~
Qiang Xue committed
65 66 67
	 *
	 * If no renderer is available for the given view file, the view file will be treated as a normal PHP
	 * and rendered via [[renderPhpFile()]].
Qiang Xue committed
68
	 */
69
	public $renderers;
70 71 72
	/**
	 * @var string the default view file extension. This will be appended to view file names if they don't have file extensions.
	 */
73
	public $defaultExtension = 'php';
74
	/**
75
	 * @var Theme|array the theme object or the configuration array for creating the theme object.
Qiang Xue committed
76
	 * If not set, it means theming is not enabled.
77
	 */
Qiang Xue committed
78
	public $theme;
Qiang Xue committed
79
	/**
Qiang Xue committed
80 81
	 * @var array a list of named output blocks. The keys are the block names and the values
	 * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]]
82
	 * to capture small fragments of a view. They can be later accessed somewhere else
Qiang Xue committed
83 84
	 * through this property.
	 */
Qiang Xue committed
85
	public $blocks;
Qiang Xue committed
86 87
	/**
	 * @var array a list of currently active fragment cache widgets. This property
88 89
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
90
	 */
Alexander Makarov committed
91
	public $cacheStack = [];
Qiang Xue committed
92 93
	/**
	 * @var array a list of placeholders for embedding dynamic contents. This property
94 95
	 * is used internally to implement the content caching feature. Do not modify it directly.
	 * @internal
Qiang Xue committed
96
	 */
Alexander Makarov committed
97
	public $dynamicPlaceholders = [];
98

99
	/**
100 101
	 * @var array the view files currently being rendered. There may be multiple view files being
	 * rendered at a moment because one may render a view file within another.
102
	 */
103
	private $_viewFiles = [];
Qiang Xue committed
104 105


Qiang Xue committed
106
	/**
Qiang Xue committed
107
	 * Initializes the view component.
Qiang Xue committed
108
	 */
Qiang Xue committed
109
	public function init()
Qiang Xue committed
110
	{
Qiang Xue committed
111 112
		parent::init();
		if (is_array($this->theme)) {
113 114 115
			if (!isset($this->theme['class'])) {
				$this->theme['class'] = 'yii\base\Theme';
			}
Qiang Xue committed
116
			$this->theme = Yii::createObject($this->theme);
Qiang Xue committed
117 118 119
		}
	}

Qiang Xue committed
120
	/**
Qiang Xue committed
121
	 * Renders a view.
Qiang Xue committed
122
	 *
123
	 * The view to be rendered can be specified in one of the following formats:
Qiang Xue committed
124
	 *
125 126 127 128 129 130
	 * - path alias (e.g. "@app/views/site/index");
	 * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
	 *   The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
	 * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
	 *   The actual view file will be looked for under the [[Module::viewPath|view path]] of [[module]].
	 * - resolving any other format will be performed via [[ViewContext::findViewFile()]].
Qiang Xue committed
131 132 133
	 *
	 * @param string $view the view name. Please refer to [[Controller::findViewFile()]]
	 * and [[Widget::findViewFile()]] on how to specify this parameter.
Qiang Xue committed
134
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
135 136
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
137
	 * @return string the rendering result
Qiang Xue committed
138
	 * @throws InvalidParamException if the view cannot be resolved or the view file does not exist.
139
	 * @see renderFile()
Qiang Xue committed
140
	 */
141
	public function render($view, $params = [], $context = null)
Qiang Xue committed
142
	{
143 144 145 146 147 148 149 150 151 152 153
		$viewFile = $this->findViewFile($view, $context);
		return $this->renderFile($viewFile, $params, $context);
	}

	/**
	 * Finds the view file based on the given view name.
	 * @param string $view the view name or the path alias of the view file. Please refer to [[render()]]
	 * on how to specify this parameter.
	 * @param object $context the context that the view should be used to search the view file. If null,
	 * existing [[context]] will be used.
	 * @return string the view file path. Note that the file may not exist.
154
	 * @throws InvalidCallException if [[context]] is required and invalid.
155 156 157 158 159 160 161 162 163
	 */
	protected function findViewFile($view, $context = null)
	{
		if (strncmp($view, '@', 1) === 0) {
			// e.g. "@app/views/main"
			$file = Yii::getAlias($view);
		} elseif (strncmp($view, '//', 2) === 0) {
			// e.g. "//layouts/main"
			$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
164
		} elseif (strncmp($view, '/', 1) === 0) {
165
			// e.g. "/site/index"
166 167 168 169 170
			if (Yii::$app->controller !== null) {
				$file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
			} else {
				throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
			}
Qiang Xue committed
171
		} else {
172 173 174 175
			// context required
			if ($context === null) {
				$context = $this->context;
			}
176
			if ($context instanceof ViewContextInterface) {
177 178
				$file = $context->findViewFile($view);
			} else {
179
				throw new InvalidCallException("Unable to locate view file for view '$view': no active view context.");
180
			}
Qiang Xue committed
181
		}
182

183 184 185 186 187 188 189 190
		if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
			return $file;
		}
		$path = $file . '.' . $this->defaultExtension;
		if ($this->defaultExtension !== 'php' && !is_file($path)) {
			$path = $file . '.php';
		}
		return $path;
Qiang Xue committed
191 192
	}

Qiang Xue committed
193 194
	/**
	 * Renders a view file.
Qiang Xue committed
195
	 *
Qiang Xue committed
196 197
	 * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
	 * as it is available.
Qiang Xue committed
198
	 *
Qiang Xue committed
199 200 201 202 203 204
	 * The method will call [[FileHelper::localize()]] to localize the view file.
	 *
	 * If [[renderer]] is enabled (not null), the method will use it to render the view file.
	 * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
	 * return it as a string.
	 *
Qiang Xue committed
205
	 * @param string $viewFile the view file. This can be either a file path or a path alias.
Qiang Xue committed
206
	 * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
Qiang Xue committed
207 208
	 * @param object $context the context that the view should use for rendering the view. If null,
	 * existing [[context]] will be used.
Qiang Xue committed
209
	 * @return string the rendering result
Qiang Xue committed
210
	 * @throws InvalidParamException if the view file does not exist
Qiang Xue committed
211
	 */
Alexander Makarov committed
212
	public function renderFile($viewFile, $params = [], $context = null)
Qiang Xue committed
213
	{
Qiang Xue committed
214
		$viewFile = Yii::getAlias($viewFile);
215 216 217
		if ($this->theme !== null) {
			$viewFile = $this->theme->applyTo($viewFile);
		}
Qiang Xue committed
218 219 220 221 222 223
		if (is_file($viewFile)) {
			$viewFile = FileHelper::localize($viewFile);
		} else {
			throw new InvalidParamException("The view file does not exist: $viewFile");
		}

Qiang Xue committed
224
		$oldContext = $this->context;
Qiang Xue committed
225 226 227
		if ($context !== null) {
			$this->context = $context;
		}
228
		$output = '';
229 230
		$this->_viewFiles[] = $viewFile;

231
		if ($this->beforeRender()) {
Qiang Xue committed
232
			Yii::trace("Rendering view file: $viewFile", __METHOD__);
Qiang Xue committed
233 234
			$ext = pathinfo($viewFile, PATHINFO_EXTENSION);
			if (isset($this->renderers[$ext])) {
Qiang Xue committed
235
				if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
Qiang Xue committed
236 237 238 239 240
					$this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
				}
				/** @var ViewRenderer $renderer */
				$renderer = $this->renderers[$ext];
				$output = $renderer->render($this, $viewFile, $params);
241 242 243
			} else {
				$output = $this->renderPhpFile($viewFile, $params);
			}
244
			$this->afterRender($output);
Qiang Xue committed
245
		}
Qiang Xue committed
246

247
		array_pop($this->_viewFiles);
Qiang Xue committed
248 249 250
		$this->context = $oldContext;

		return $output;
Qiang Xue committed
251 252
	}

253 254 255 256 257 258 259 260
	/**
	 * @return string|boolean the view file currently being rendered. False if no view file is being rendered.
	 */
	public function getViewFile()
	{
		return end($this->_viewFiles);
	}

261 262 263 264 265 266
	/**
	 * This method is invoked right before [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @return boolean whether to continue rendering the view file.
	 */
267
	public function beforeRender()
268
	{
269
		$event = new ViewEvent;
270 271 272 273 274 275 276 277 278 279 280
		$this->trigger(self::EVENT_BEFORE_RENDER, $event);
		return $event->isValid;
	}

	/**
	 * This method is invoked right after [[renderFile()]] renders a view file.
	 * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
	 * If you override this method, make sure you call the parent implementation first.
	 * @param string $output the rendering result of the view file. Updates to this parameter
	 * will be passed back and returned by [[renderFile()]].
	 */
281
	public function afterRender(&$output)
282 283
	{
		if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
284
			$event = new ViewEvent;
285 286 287 288 289 290
			$event->output = $output;
			$this->trigger(self::EVENT_AFTER_RENDER, $event);
			$output = $event->output;
		}
	}

Qiang Xue committed
291
	/**
Qiang Xue committed
292 293 294 295 296 297
	 * Renders a view file as a PHP script.
	 *
	 * This method treats the view file as a PHP script and includes the file.
	 * It extracts the given parameters and makes them available in the view file.
	 * The method captures the output of the included view file and returns it as a string.
	 *
Qiang Xue committed
298 299
	 * This method should mainly be called by view renderer or [[renderFile()]].
	 *
Qiang Xue committed
300 301 302
	 * @param string $_file_ the view file.
	 * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
	 * @return string the rendering result
Qiang Xue committed
303
	 */
Alexander Makarov committed
304
	public function renderPhpFile($_file_, $_params_ = [])
Qiang Xue committed
305
	{
Qiang Xue committed
306 307 308 309 310
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
311 312
	}

Qiang Xue committed
313 314 315 316 317 318 319 320 321
	/**
	 * Renders dynamic content returned by the given PHP statements.
	 * This method is mainly used together with content caching (fragment caching and page caching)
	 * when some portions of the content (called *dynamic content*) should not be cached.
	 * The dynamic content must be returned by some PHP statements.
	 * @param string $statements the PHP statements for generating the dynamic content.
	 * @return string the placeholder of the dynamic content, or the dynamic content if there is no
	 * active content cache currently.
	 */
Qiang Xue committed
322 323
	public function renderDynamic($statements)
	{
Qiang Xue committed
324 325
		if (!empty($this->cacheStack)) {
			$n = count($this->dynamicPlaceholders);
Qiang Xue committed
326
			$placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
Qiang Xue committed
327
			$this->addDynamicPlaceholder($placeholder, $statements);
Qiang Xue committed
328 329 330 331 332 333
			return $placeholder;
		} else {
			return $this->evaluateDynamicContent($statements);
		}
	}

Qiang Xue committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
	/**
	 * Adds a placeholder for dynamic content.
	 * This method is internally used.
	 * @param string $placeholder the placeholder name
	 * @param string $statements the PHP statements for generating the dynamic content
	 */
	public function addDynamicPlaceholder($placeholder, $statements)
	{
		foreach ($this->cacheStack as $cache) {
			$cache->dynamicPlaceholders[$placeholder] = $statements;
		}
		$this->dynamicPlaceholders[$placeholder] = $statements;
	}

	/**
	 * Evaluates the given PHP statements.
	 * This method is mainly used internally to implement dynamic content feature.
	 * @param string $statements the PHP statements to be evaluated.
	 * @return mixed the return value of the PHP statements.
	 */
Qiang Xue committed
354 355 356 357 358
	public function evaluateDynamicContent($statements)
	{
		return eval($statements);
	}

Qiang Xue committed
359
	/**
Qiang Xue committed
360
	 * Begins recording a block.
361
	 * This method is a shortcut to beginning [[Block]]
Qiang Xue committed
362 363 364
	 * @param string $id the block ID.
	 * @param boolean $renderInPlace whether to render the block content in place.
	 * Defaults to false, meaning the captured block will not be displayed.
365
	 * @return Block the Block widget instance
Qiang Xue committed
366
	 */
Qiang Xue committed
367
	public function beginBlock($id, $renderInPlace = false)
Qiang Xue committed
368
	{
Alexander Makarov committed
369
		return Block::begin([
Qiang Xue committed
370 371
			'id' => $id,
			'renderInPlace' => $renderInPlace,
372
			'view' => $this,
Alexander Makarov committed
373
		]);
Qiang Xue committed
374 375 376
	}

	/**
Qiang Xue committed
377
	 * Ends recording a block.
Qiang Xue committed
378
	 */
Qiang Xue committed
379
	public function endBlock()
Qiang Xue committed
380
	{
381
		Block::end();
Qiang Xue committed
382 383
	}

Qiang Xue committed
384 385
	/**
	 * Begins the rendering of content that is to be decorated by the specified view.
Qiang Xue committed
386
	 * This method can be used to implement nested layout. For example, a layout can be embedded
Sergey Gonimar committed
387
	 * in another layout file specified as '@app/views/layouts/base.php' like the following:
Qiang Xue committed
388 389
	 *
	 * ~~~
Sergey Gonimar committed
390
	 * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
Qiang Xue committed
391 392 393 394 395 396
	 * ...layout content here...
	 * <?php $this->endContent(); ?>
	 * ~~~
	 *
	 * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
	 * This can be specified as either the view file path or path alias.
resurtm committed
397
	 * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
398 399
	 * @return ContentDecorator the ContentDecorator widget instance
	 * @see ContentDecorator
Qiang Xue committed
400
	 */
Alexander Makarov committed
401
	public function beginContent($viewFile, $params = [])
Qiang Xue committed
402
	{
Alexander Makarov committed
403
		return ContentDecorator::begin([
Qiang Xue committed
404
			'viewFile' => $viewFile,
Qiang Xue committed
405
			'params' => $params,
406
			'view' => $this,
Alexander Makarov committed
407
		]);
Qiang Xue committed
408 409 410 411 412 413 414
	}

	/**
	 * Ends the rendering of content.
	 */
	public function endContent()
	{
415
		ContentDecorator::end();
Qiang Xue committed
416 417
	}

418 419 420 421 422 423 424 425
	/**
	 * Begins fragment caching.
	 * This method will display cached content if it is available.
	 * If not, it will start caching and would expect an [[endCache()]]
	 * call to end the cache and save the content into cache.
	 * A typical usage of fragment caching is as follows,
	 *
	 * ~~~
resurtm committed
426
	 * if ($this->beginCache($id)) {
427 428 429 430 431 432
	 *     // ...generate content here
	 *     $this->endCache();
	 * }
	 * ~~~
	 *
	 * @param string $id a unique ID identifying the fragment to be cached.
433
	 * @param array $properties initial property values for [[FragmentCache]]
434 435 436
	 * @return boolean whether you should generate the content for caching.
	 * False if the cached version is available.
	 */
Alexander Makarov committed
437
	public function beginCache($id, $properties = [])
438 439
	{
		$properties['id'] = $id;
440
		$properties['view'] = $this;
slavcodev committed
441
		/** @var FragmentCache $cache */
442
		$cache = FragmentCache::begin($properties);
Qiang Xue committed
443
		if ($cache->getCachedContent() !== false) {
444 445 446 447 448 449 450 451 452 453 454 455
			$this->endCache();
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Ends fragment caching.
	 */
	public function endCache()
	{
456
		FragmentCache::end();
457
	}
458 459

	/**
Alexander Makarov committed
460
	 * Marks the beginning of a page.
461 462 463 464 465
	 */
	public function beginPage()
	{
		ob_start();
		ob_implicit_flush(false);
466 467

		$this->trigger(self::EVENT_BEGIN_PAGE);
468 469 470
	}

	/**
Alexander Makarov committed
471
	 * Marks the ending of a page.
472 473 474
	 */
	public function endPage()
	{
475
		$this->trigger(self::EVENT_END_PAGE);
Alexander Makarov committed
476
		ob_end_flush();
477
	}
Zander Baldwin committed
478
}