View.php 17.5 KB
Newer Older
Qiang Xue committed
1 2 3 4 5
<?php
/**
 * View class file.
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9 10 11
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

Qiang Xue committed
12
use Yii;
Qiang Xue committed
13
use yii\util\FileHelper;
Qiang Xue committed
14
use yii\base\Application;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17 18 19 20
 * View represents a view object in the MVC pattern.
 * 
 * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
 * 
Qiang Xue committed
21 22 23 24 25
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class View extends Component
{
Qiang Xue committed
26
	/**
Qiang Xue committed
27 28 29 30
	 * @var object the object that owns this view. This can be a controller, a widget, or any other object.
	 */
	public $owner;
	/**
Qiang Xue committed
31 32
	 * @var string the layout to be applied when [[render()]] or [[renderContent()]] is called.
	 * If not set, it will use the [[Module::layout]] of the currently active module.
Qiang Xue committed
33
	 */
Qiang Xue committed
34
	public $layout;
Qiang Xue committed
35 36 37 38 39 40 41 42 43 44
	/**
	 * @var string the language that the view should be rendered in. If not set, it will use
	 * the value of [[Application::language]].
	 */
	public $language;
	/**
	 * @var string the language that the original view is in. If not set, it will use
	 * the value of [[Application::sourceLanguage]].
	 */
	public $sourceLanguage;
Qiang Xue committed
45 46 47 48 49
	/**
	 * @var boolean whether to localize the view when possible. Defaults to true.
	 * Note that when this is true, if a localized view cannot be found, the original view will be rendered.
	 * No error will be reported.
	 */
Qiang Xue committed
50
	public $enableI18N = true;
Qiang Xue committed
51 52
	/**
	 * @var boolean whether to theme the view when possible. Defaults to true.
Qiang Xue committed
53
	 * Note that theming will be disabled if [[Application::theme]] is not set.
Qiang Xue committed
54
	 */
Qiang Xue committed
55
	public $enableTheme = true;
56 57 58 59
	/**
	 * @var mixed custom parameters that are available in the view template
	 */
	public $params;
Qiang Xue committed
60

Qiang Xue committed
61 62 63
	/**
	 * @var Widget[] the widgets that are currently not ended
	 */
Qiang Xue committed
64
	private  $_widgetStack = array();
Qiang Xue committed
65

Qiang Xue committed
66 67
	/**
	 * Constructor.
Qiang Xue committed
68
	 * @param object $owner the owner of this view. This usually is a controller or a widget.
Qiang Xue committed
69
	 * @param array $config name-value pairs that will be used to initialize the object properties
Qiang Xue committed
70
	 */
Qiang Xue committed
71
	public function __construct($owner, $config = array())
Qiang Xue committed
72
	{
Qiang Xue committed
73
		$this->owner = $owner;
Qiang Xue committed
74
		parent::__construct($config);
Qiang Xue committed
75 76
	}

Qiang Xue committed
77
	/**
Qiang Xue committed
78 79
	 * Renders a view within a layout.
	 * This method is similar to [[renderPartial()]] except that if a layout is available,
Qiang Xue committed
80
	 * this method will embed the view result into the layout and then return it.
Qiang Xue committed
81
	 * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name.
Qiang Xue committed
82 83 84
	 * @param array $params the parameters that should be made available in the view. The PHP function `extract()`
	 * will be called on this variable to extract the variables from this parameter.
	 * @return string the rendering result
Qiang Xue committed
85 86 87
	 * @throws InvalidConfigException if the view file or layout file cannot be found
	 * @see findViewFile()
	 * @see findLayoutFile()
Qiang Xue committed
88
	 */
Qiang Xue committed
89 90 91
	public function render($view, $params = array())
	{
		$content = $this->renderPartial($view, $params);
Qiang Xue committed
92
		return $this->renderContent($content);
Qiang Xue committed
93 94
	}

Qiang Xue committed
95
	/**
Qiang Xue committed
96 97 98
	 * Renders a text content within a layout.
	 * The layout being used is resolved by [[findLayout()]].
	 * If no layout is available, the content will be returned back.
Qiang Xue committed
99 100
	 * @param string $content the content to be rendered
	 * @return string the rendering result
Qiang Xue committed
101 102
	 * @throws InvalidConfigException if the layout file cannot be found
	 * @see findLayoutFile()
Qiang Xue committed
103 104
	 */
	public function renderContent($content)
Qiang Xue committed
105 106 107
	{
		$layoutFile = $this->findLayoutFile();
		if ($layoutFile !== false) {
Qiang Xue committed
108
			return $this->renderFile($layoutFile, array('content' => $content));
Qiang Xue committed
109
		} else {
Qiang Xue committed
110
			return $content;
Qiang Xue committed
111 112 113
		}
	}

Qiang Xue committed
114 115 116
	/**
	 * Renders a view.
	 *
Qiang Xue committed
117
	 * The method first finds the actual view file corresponding to the specified view.
Qiang Xue committed
118 119 120
	 * It then calls [[renderFile()]] to render the view file. The rendering result is returned
	 * as a string. If the view file does not exist, an exception will be thrown.
	 *
Qiang Xue committed
121
	 * @param string $view the view to be rendered. Please refer to [[findViewFile()]] on possible formats of the view name.
Qiang Xue committed
122 123
	 * @param array $params the parameters that should be made available in the view. The PHP function `extract()`
	 * will be called on this variable to extract the variables from this parameter.
124
	 * @return string the rendering result
Qiang Xue committed
125
	 * @throws InvalidCallException if the view file cannot be found
Qiang Xue committed
126
	 * @see findViewFile()
Qiang Xue committed
127
	 */
Qiang Xue committed
128
	public function renderPartial($view, $params = array())
Qiang Xue committed
129 130 131
	{
		$file = $this->findViewFile($view);
		if ($file !== false) {
Qiang Xue committed
132
			return $this->renderFile($file, $params);
Qiang Xue committed
133
		} else {
Qiang Xue committed
134
			throw new InvalidCallException("Unable to find the view file for view '$view'.");
Qiang Xue committed
135 136 137
		}
	}

Qiang Xue committed
138 139
	/**
	 * Renders a view file.
Qiang Xue committed
140
	 *
Qiang Xue committed
141 142 143 144 145 146 147
	 * If a [[ViewRenderer|view renderer]] is installed, this method will try to use the view renderer
	 * to render the view file. Otherwise, it will simply include the view file, capture its output
	 * and return it as a string.
	 *
	 * @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
148
	 */
Qiang Xue committed
149
	public function renderFile($file, $params = array())
Qiang Xue committed
150
	{
Qiang Xue committed
151
		$renderer = Yii::$app->getViewRenderer();
Qiang Xue committed
152 153
		if ($renderer !== null) {
			return $renderer->render($this, $file, $params);
Qiang Xue committed
154
		} else {
Qiang Xue committed
155
			return $this->renderPhpFile($file, $params);
Qiang Xue committed
156 157 158 159
		}
	}

	/**
Qiang Xue committed
160 161 162 163 164 165 166 167 168
	 * 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.
	 *
	 * @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
169
	 */
Qiang Xue committed
170
	public function renderPhpFile($_file_, $_params_ = array())
Qiang Xue committed
171
	{
Qiang Xue committed
172 173 174 175 176
		ob_start();
		ob_implicit_flush(false);
		extract($_params_, EXTR_OVERWRITE);
		require($_file_);
		return ob_get_clean();
Qiang Xue committed
177 178
	}

Qiang Xue committed
179 180 181 182 183 184 185
	/**
	 * Creates a widget.
	 * This method will use [[Yii::createObject()]] to create the widget.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @return Widget the newly created widget instance
	 */
Qiang Xue committed
186 187 188
	public function createWidget($class, $properties = array())
	{
		$properties['class'] = $class;
Qiang Xue committed
189
		return Yii::createObject($properties, $this->owner);
Qiang Xue committed
190 191
	}

Qiang Xue committed
192 193 194 195 196 197 198 199 200 201
	/**
	 * Creates and runs a widget.
	 * Compared with [[createWidget()]], this method does one more thing: it will
	 * run the widget after it is created.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
	 * @param boolean $captureOutput whether to capture the output of the widget and return it as a string
	 * @return string|Widget if $captureOutput is true, the output of the widget will be returned;
	 * otherwise the widget object will be returned.
	 */
Qiang Xue committed
202
	public function widget($class, $properties = array(), $captureOutput = false)
Qiang Xue committed
203
	{
Qiang Xue committed
204 205 206 207 208 209 210 211 212 213 214
		if ($captureOutput) {
			ob_start();
			ob_implicit_flush(false);
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return ob_get_clean();
		} else {
			$widget = $this->createWidget($class, $properties);
			$widget->run();
			return $widget;
		}
Qiang Xue committed
215 216
	}

Qiang Xue committed
217 218
	/**
	 * Begins a widget.
Qiang Xue committed
219 220 221 222
	 * This method is similar to [[createWidget()]] except that it will expect a matching
	 * [[endWidget()]] call after this.
	 * @param string $class the widget class name or path alias
	 * @param array $properties the initial property values of the widget.
Qiang Xue committed
223 224
	 * @return Widget the widget instance
	 */
Qiang Xue committed
225 226
	public function beginWidget($class, $properties = array())
	{
227
		$widget = $this->createWidget($class, $properties);
Qiang Xue committed
228
		$this->_widgetStack[] = $widget;
229
		return $widget;
Qiang Xue committed
230 231
	}

Qiang Xue committed
232 233 234 235 236 237 238 239
	/**
	 * Ends a widget.
	 * Note that the rendering result of the widget is directly echoed out.
	 * If you want to capture the rendering result of a widget, you may use
	 * [[createWidget()]] and [[Widget::run()]].
	 * @return Widget the widget instance
	 * @throws Exception if [[beginWidget()]] and [[endWidget()]] calls are not properly nested
	 */
Qiang Xue committed
240
	public function endWidget()
Qiang Xue committed
241
	{
Qiang Xue committed
242 243
		$widget = array_pop($this->_widgetStack);
		if ($widget instanceof Widget) {
Qiang Xue committed
244
			$widget->run();
Qiang Xue committed
245
			return $widget;
246 247 248 249
		} else {
			throw new Exception("Unmatched beginWidget() and endWidget() calls.");
		}
	}
Qiang Xue committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
//
//	/**
//	 * Begins recording a clip.
//	 * This method is a shortcut to beginning [[yii\widgets\Clip]]
//	 * @param string $id the clip ID.
//	 * @param array $properties initial property values for [[yii\widgets\Clip]]
//	 */
//	public function beginClip($id, $properties = array())
//	{
//		$properties['id'] = $id;
//		$this->beginWidget('yii\widgets\Clip', $properties);
//	}
//
//	/**
//	 * Ends recording a clip.
//	 */
//	public function endClip()
//	{
//		$this->endWidget();
//	}
//
//	/**
//	 * 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,
//	 *
//	 * ~~~
//	 * if($this->beginCache($id)) {
//	 *     // ...generate content here
//	 *     $this->endCache();
//	 * }
//	 * ~~~
//	 *
//	 * @param string $id a unique ID identifying the fragment to be cached.
//	 * @param array $properties initial property values for [[yii\widgets\OutputCache]]
//	 * @return boolean whether we need to generate content for caching. False if cached version is available.
//	 * @see endCache
//	 */
//	public function beginCache($id, $properties = array())
//	{
//		$properties['id'] = $id;
//		$cache = $this->beginWidget('yii\widgets\OutputCache', $properties);
//		if ($cache->getIsContentCached()) {
//			$this->endCache();
//			return false;
//		} else {
//			return true;
//		}
//	}
//
//	/**
//	 * Ends fragment caching.
//	 * This is an alias to [[endWidget()]]
//	 * @see beginCache
//	 */
//	public function endCache()
//	{
//		$this->endWidget();
//	}
//
//	/**
//	 * Begins the rendering of content that is to be decorated by the specified view.
//	 * @param mixed $view the name of the view that will be used to decorate the content. The actual view script
//	 * is resolved via {@link getViewFile}. If this parameter is null (default),
//	 * the default layout will be used as the decorative view.
//	 * Note that if the current controller does not belong to
//	 * any module, the default layout refers to the application's {@link CWebApplication::layout default layout};
//	 * If the controller belongs to a module, the default layout refers to the module's
//	 * {@link CWebModule::layout default layout}.
//	 * @param array $params the variables (name=>value) to be extracted and made available in the decorative view.
//	 * @see endContent
//	 * @see yii\widgets\ContentDecorator
//	 */
//	public function beginContent($view, $params = array())
//	{
//		$this->beginWidget('yii\widgets\ContentDecorator', array(
//			'view' => $view,
//			'params' => $params,
//		));
//	}
//
//	/**
//	 * Ends the rendering of content.
//	 * @see beginContent
//	 */
//	public function endContent()
//	{
//		$this->endWidget();
//	}
Qiang Xue committed
341

Qiang Xue committed
342 343
	/**
	 * Finds the view file based on the given view name.
Qiang Xue committed
344
	 *
Qiang Xue committed
345 346
	 * A view name can be specified in one of the following formats:
	 *
Qiang Xue committed
347
	 * - path alias (e.g. "@app/views/site/index");
Qiang Xue committed
348 349 350 351 352 353 354 355 356
	 * - 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 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 the currently
	 *   active module.
	 * - relative path (e.g. "index"): the actual view file will be looked for under the [[owner]]'s view path.
	 *   If [[owner]] is a widget or a controller, its view path is given by their `viewPath` property.
	 *   If [[owner]] is an object of any other type, its view path is the `view` sub-directory of the directory
	 *   containing the owner class file.
Qiang Xue committed
357
	 *
Qiang Xue committed
358
	 * If the view name does not contain a file extension, it will default to `.php`.
Qiang Xue committed
359 360 361 362
	 *
	 * If [[enableTheme]] is true and there is an active application them, the method will also
	 * attempt to use a themed version of the view file, when available.
	 *
Qiang Xue committed
363 364 365
	 * And if [[enableI18N]] is true, the method will attempt to use a translated version of the view file,
	 * when available.
	 *
Qiang Xue committed
366 367
	 * @param string $view the view name or path alias. If the view name does not specify
	 * the view file extension name, it will use `.php` as the extension name.
Qiang Xue committed
368 369
	 * @return string the view file path if it exists. False if the view file cannot be found.
	 * @throws InvalidConfigException if the view file does not exist
Qiang Xue committed
370
	 */
Qiang Xue committed
371
	public function findViewFile($view)
Qiang Xue committed
372
	{
Qiang Xue committed
373
		if (FileHelper::getExtension($view) === '') {
Qiang Xue committed
374
			$view .= '.php';
Qiang Xue committed
375
		}
Qiang Xue committed
376
		if (strncmp($view, '@', 1) === 0) {
Qiang Xue committed
377
			// e.g. "@app/views/common"
Qiang Xue committed
378 379 380
			if (($file = Yii::getAlias($view)) === false) {
				throw new InvalidConfigException("Invalid path alias: $view");
			}
Qiang Xue committed
381
		} elseif (strncmp($view, '/', 1) !== 0) {
Qiang Xue committed
382
			// e.g. "index"
Qiang Xue committed
383 384 385 386 387
			if ($this->owner instanceof Controller || $this->owner instanceof Widget) {
				$file = $this->owner->getViewPath() . DIRECTORY_SEPARATOR . $view;
			} elseif ($this->owner !== null) {
				$class = new \ReflectionClass($this->owner);
				$file = dirname($class->getFileName()) . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
388
			} else {
Qiang Xue committed
389
				$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
390
			}
Qiang Xue committed
391
		} elseif (strncmp($view, '//', 2) !== 0 && Yii::$app->controller !== null) {
Qiang Xue committed
392
			// e.g. "/site/index"
Qiang Xue committed
393
			$file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
Qiang Xue committed
394
		} else {
Qiang Xue committed
395
			// e.g. "//layouts/main"
Qiang Xue committed
396
			$file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
Qiang Xue committed
397 398
		}

Qiang Xue committed
399
		if (is_file($file)) {
Qiang Xue committed
400
			if ($this->enableTheme && ($theme = Yii::$app->getTheme()) !== null) {
Qiang Xue committed
401 402 403
				$file = $theme->apply($file);
			}
			return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file;
Qiang Xue committed
404
		} else {
Qiang Xue committed
405
			throw new InvalidConfigException("View file for view '$view' does not exist: $file");
Qiang Xue committed
406 407 408 409
		}
	}

	/**
Qiang Xue committed
410
	 * Finds the layout file that can be applied to the view.
Qiang Xue committed
411
	 *
Qiang Xue committed
412
	 * The applicable layout is resolved according to the following rules:
Qiang Xue committed
413
	 *
Qiang Xue committed
414 415 416 417 418 419
	 * - If [[layout]] is specified as a string, use it as the layout name and search for the layout file
	 *   under the layout path of the currently active module;
	 * - If [[layout]] is null and [[owner]] is a controller:
	 *      * If the controller's [[Controller::layout|layout]] is a string, use it as the layout name
	 *        and search for the layout file under the layout path of the parent module of the controller;
	 *      * If the controller's [[Controller::layout|layout]] is null, look through its ancestor modules
Qiang Xue committed
420 421
	 *        and find the first one whose [[Module::layout|layout]] is not null. Use the layout specified
	 *        by that module;
Qiang Xue committed
422
	 * - Returns false for all other cases.
Qiang Xue committed
423
	 *
Qiang Xue committed
424 425
	 * Like view names, a layout name can take several formats:
	 *
Qiang Xue committed
426
	 * - path alias (e.g. "@app/views/layouts/main");
Qiang Xue committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
	 * - absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
	 *   looked for under the [[Application::layoutPath|layout path]] of the application;
	 * - relative path (e.g. "main"): the actual layout layout file will be looked for under the
	 *   [[Module::viewPath|view path]] of the context module determined by the above layout resolution process.
	 *
	 * If the layout name does not contain a file extension, it will default to `.php`.
	 *
	 * If [[enableTheme]] is true and there is an active application them, the method will also
	 * attempt to use a themed version of the layout file, when available.
	 *
	 * And if [[enableI18N]] is true, the method will attempt to use a translated version of the layout file,
	 * when available.
	 *
	 * @return string|boolean the layout file path, or false if layout is not needed.
	 * @throws InvalidConfigException if the layout file cannot be found
Qiang Xue committed
442 443 444
	 */
	public function findLayoutFile()
	{
Qiang Xue committed
445
		/** @var $module Module */
Qiang Xue committed
446
		if (is_string($this->layout)) {
Qiang Xue committed
447 448
			if (Yii::$app->controller) {
				$module = Yii::$app->controller->module;
Qiang Xue committed
449
			} else {
Qiang Xue committed
450
				$module = Yii::$app;
Qiang Xue committed
451 452
			}
			$view = $this->layout;
Qiang Xue committed
453
		} elseif ($this->owner instanceof Controller) {
Qiang Xue committed
454 455 456 457 458 459 460 461
			if (is_string($this->owner->layout)) {
				$module = $this->owner->module;
				$view = $this->owner->layout;
			} elseif ($this->owner->layout === null) {
				$module = $this->owner->module;
				while ($module !== null && $module->layout === null) {
					$module = $module->module;
				}
Qiang Xue committed
462 463
				if ($module !== null && is_string($module->layout)) {
					$view = $module->layout;
Qiang Xue committed
464 465
				}
			}
Qiang Xue committed
466 467 468
		}

		if (!isset($view)) {
Qiang Xue committed
469 470 471
			return false;
		}

Qiang Xue committed
472
		if (FileHelper::getExtension($view) === '') {
Qiang Xue committed
473 474 475
			$view .= '.php';
		}
		if (strncmp($view, '@', 1) === 0) {
Qiang Xue committed
476 477
			if (($file = Yii::getAlias($view)) === false) {
				throw new InvalidConfigException("Invalid path alias: $view");
Qiang Xue committed
478
			}
Qiang Xue committed
479
		} elseif (strncmp($view, '/', 1) === 0) {
Qiang Xue committed
480
			$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
481
		} else {
Qiang Xue committed
482
			$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
Qiang Xue committed
483
		}
Qiang Xue committed
484 485

		if (is_file($file)) {
Qiang Xue committed
486
			if ($this->enableTheme && ($theme = Yii::$app->getTheme()) !== null) {
Qiang Xue committed
487 488 489
				$file = $theme->apply($file);
			}
			return $this->enableI18N ? FileHelper::localize($file, $this->language, $this->sourceLanguage) : $file;
490
		} else {
Qiang Xue committed
491
			throw new InvalidConfigException("Layout file for layout '$view' does not exist: $file");
492
		}
Qiang Xue committed
493
	}
Qiang Xue committed
494
}