Skip to content
PHP Ecosystem
Explore

View

API reference › yii › web › View

View represents a view object in the MVC pattern.

View provides a set of methods (e.g. render()) for rendering purpose.

View is configured as an application component in Application by default. You can access that instance via Yii::$app->view.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'view' => [
'theme' => 'app\themes\MyTheme',
'renderers' => [
// you may add Smarty or Twig renderer here
]
// ...
]

For more details and usage information on View, see the guide article on views.

PropertyTypeDescriptionDefined by
$assetBundlesarray<string, AssetBundle|bool>List of the registered asset bundles. Default: [].View
$assetManagerAssetManagerThe asset manager.View
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$blocksarrayA list of named output blocks. Default: null.yii\base\View
$contextyii\base\ViewContextInterfaceThe context under which the renderFile() method is being invoked. Default: null.yii\base\View
$cssarrayThe registered CSS code blocks. Default: [].View
$cssFilesarrayThe registered CSS files. Default: [].View
$defaultExtensionstringThe default view file extension. Default: 'php'.yii\base\View
$dynamicContents read-onlyyii\base\DynamicContentAwareInterface[]Class instances supporting dynamic contents.yii\base\View
$dynamicPlaceholdersarrayA list of placeholders.yii\base\View
$jsarrayThe registered JS code blocks Default: [].View
$jsFilesarrayThe registered JS files. Default: [].View
$linkTagsarrayThe registered link tags. Default: [].View
$metaTagsarrayThe registered meta tags. Default: [].View
$paramsarrayCustom parameters that are shared among view templates. Default: [].yii\base\View
$renderersarray|nullA list of available renderers indexed by their corresponding supported file extensions. Default: null.yii\base\View
$scriptOptionsarrayThe script tag options. Default: []. Available since 2.0.50.View
$styleOptionsarrayThe style tag options. Default: []. Available since 2.0.53.View
$themeyii\base\Theme|array|string|nullThe theme object or the configuration for creating the theme object. Default: null.yii\base\View
$titlestringThe page title Default: null.View
$viewFile read-onlystring|boolThe view file currently being rendered.yii\base\View
$isPageEnded protectedboolWhether endPage() has been called and all files have been registered Default: false. Available since 2.0.44.View
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addDynamicPlaceholder()Adds a placeholder for dynamic content.yii\base\View
afterRender()This method is invoked right after renderFile() renders a view file.yii\base\View
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
beforeRender()This method is invoked right before renderFile() renders a view file.yii\base\View
beginBlock()Begins recording a block.yii\base\View
beginBody()Marks the beginning of an HTML body section.View
beginCache()Begins fragment caching.yii\base\View
beginContent()Begins the rendering of content that is to be decorated by the specified view.yii\base\View
beginPage()Marks the beginning of a page.yii\base\View
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
clear()Clears up the registered meta tags, link tags, css/js scripts and files.View
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
endBlock()Ends recording a block.yii\base\View
endBody()Marks the ending of an HTML body section.View
endCache()Ends fragment caching.yii\base\View
endContent()Ends the rendering of content.yii\base\View
endPage()Marks the ending of an HTML page.View
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
evaluateDynamicContent()Evaluates the given PHP statements.yii\base\View
getAssetManager()Registers the asset manager being used by this view object.View
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getDynamicContents()Returns a list of currently active dynamic content class instances.yii\base\View
getDynamicPlaceholders()Returns a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.yii\base\View
getViewFile()yii\base\View
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
head()Marks the position of an HTML head section.View
init()Initializes the view component.yii\base\View
off()Detaches an existing event handler from this component.yii\base\Component
on()Attaches an event handler to an event.yii\base\Component
popDynamicContent()Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class instances.yii\base\View
pushDynamicContent()Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class instances.yii\base\View
registerAssetBundle()Registers the named asset bundle.View
registerCsrfMetaTags()Registers CSRF meta tags.View
registerCss()Registers a CSS code block.View
registerCssFile()Registers a CSS file.View
registerJs()Registers a JS code block.View
registerJsFile()Registers a JS file.View
registerJsVar()Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated variable names.View
registerLinkTag()Registers a link tag.View
registerMetaTag()Registers a meta tag.View
render()Renders a view.yii\base\View
renderAjax()Renders a view in response to an AJAX request.View
renderDynamic()Renders dynamic content returned by the given PHP statements.yii\base\View
renderFile()Renders a view file.yii\base\View
renderPhpFile()Renders a view file as a PHP script.yii\base\View
setAssetManager()Sets the asset manager.View
setDynamicPlaceholders()Sets a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.yii\base\View
trigger()Triggers an event.yii\base\Component
findViewFile() protectedFinds the view file based on the given view name.yii\base\View
getRequestedViewFile() protectedyii\base\View
registerAssetFiles() protectedRegisters all files provided by an asset bundle including depending bundles files.View
renderBodyBeginHtml() protectedRenders the content to be inserted at the beginning of the body section.View
renderBodyEndHtml() protectedRenders the content to be inserted at the end of the body section.View
renderHeadHtml() protectedRenders the content to be inserted in the head section.View
wrapLoadScript() protectedWraps script content for POS_LOAD position.View
wrapReadyScript() protectedWraps script content for POS_READY position.View
EventTypeDescriptionDefined by
EVENT_BEGIN_BODYyii\web\EventAn event that is triggered by beginBody(). Event name: 'beginBody'.View
EVENT_END_BODYyii\web\EventAn event that is triggered by endBody(). Event name: 'endBody'.View
EVENT_BEGIN_PAGEyii\base\EventAn event that is triggered by beginPage(). Event name: 'beginPage'.yii\base\View
EVENT_END_PAGEyii\base\EventAn event that is triggered by endPage(). Event name: 'endPage'.yii\base\View
EVENT_BEFORE_RENDERyii\base\ViewEventAn event that is triggered by renderFile() right before it renders a view file. Event name: 'beforeRender'.yii\base\View
EVENT_AFTER_RENDERyii\base\ViewEventAn event that is triggered by renderFile() right after it renders a view file. Event name: 'afterRender'.yii\base\View
ConstantValueDescriptionDefined by
POS_HEAD1The location of registered JavaScript code block or files.View
POS_BEGIN2The location of registered JavaScript code block or files.View
POS_END3The location of registered JavaScript code block or files.View
POS_READY4The location of registered JavaScript code block.View
POS_LOAD5The location of registered JavaScript code block.View
PH_HEAD'<![CDATA[YII-BLOCK-HEAD]]>'This is internally used as the placeholder for receiving the content registered for the head section.View
PH_BODY_BEGIN'<![CDATA[YII-BLOCK-BODY-BEGIN]]>'This is internally used as the placeholder for receiving the content registered for the beginning of the body section.View
PH_BODY_END'<![CDATA[YII-BLOCK-BODY-END]]>'This is internally used as the placeholder for receiving the content registered for the end of the body section.View
public array<string, yii\web\AssetBundle|bool> $assetBundles = []

List of the registered asset bundles.

The keys are the bundle names, and the values are the registered AssetBundle objects.

public yii\web\AssetManager $assetManager

The asset manager.

Defaults to the “assetManager” application component.

public function beginBody(): mixed

Marks the beginning of an HTML body section.

Returns

mixed

public function clear(): mixed

Clears up the registered meta tags, link tags, css/js scripts and files.

Returns

mixed

public function endBody(): mixed

Marks the ending of an HTML body section.

Returns

mixed

public function endPage(bool $ajaxMode = false): mixed

Marks the ending of an HTML page.

Parameters

ParameterTypeDescription
$ajaxModeboolWhether the view is rendering in AJAX mode. If true, the JS scripts registered at POS_READY and POS_LOAD positions will be rendered at the end of the view like normal scripts.

Returns

mixed

public function getAssetManager(): yii\web\AssetManager

Registers the asset manager being used by this view object.

Returns

AssetManager: The asset manager. Defaults to the “assetManager” application component.

public function head(): mixed

Marks the position of an HTML head section.

Returns

mixed

public function registerAssetBundle(string $name, int|null $position = null): yii\web\AssetBundle

Registers the named asset bundle.

All dependent asset bundles will be registered.

Parameters

ParameterTypeDescription
$namestringThe class name of the asset bundle (without the leading backslash)
$positionint|nullIf set, this forces a minimum position for javascript files. This will adjust depending assets javascript file position or fail if requirement can not be met. If this is null, asset bundles position settings will not be changed. See registerJsFile() for more details on javascript position.

Returns

AssetBundle: The registered asset bundle instance

Throws

public function registerCsrfMetaTags(): mixed

Registers CSRF meta tags.

They are rendered dynamically to retrieve a new CSRF token for each request.

$view->registerCsrfMetaTags();

The above code will result in <meta name="csrf-param" content="[yii\web\Request::$csrfParam]"> and <meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA=="> added to the page.

Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling window.yii.refreshCsrfToken() from yii.js.

Returns

mixed

Since

2.0.13

public function registerCss(string $css, array $options = [], string|null $key = null): mixed

Registers a CSS code block.

Parameters

ParameterTypeDescription
$cssstringThe content of the CSS code block to be registered
$optionsarrayThe HTML attributes for the <style>-tag.
$keystring|nullThe key that identifies the CSS code block. If null, it will use $css as the key. If two CSS code blocks are registered with the same key, the latter will overwrite the former.

Returns

mixed

public function registerCssFile(string $url, yii\web\RegisterCssFileOptions $options = [], string|null $key = null): mixed

Registers a CSS file.

This method should be used for simple registration of CSS files. If you want to use features of AssetManager like appending timestamps to the URL and file publishing options, use AssetBundle and registerAssetBundle() instead.

Parameters

ParameterTypeDescription
$urlstringThe CSS file to be registered.
$optionsyii\web\RegisterCssFileOptionsThe HTML attributes for the link tag. Please refer to Html::cssFile() for the supported options. The following options are specially handled and are not treated as HTML attributes: - depends: array, specifies the names of the asset bundles that this CSS file depends on. - appendTimestamp: bool whether to append a timestamp to the URL.
$keystring|nullThe key that identifies the CSS script file. If null, it will use $url as the key. If two CSS files are registered with the same key, the latter will overwrite the former.

Returns

mixed

Throws

public function registerJs(string $js, int $position = \self::POS_READY, string|null $key = null): mixed

Registers a JS code block.

Parameters

ParameterTypeDescription
$jsstringThe JS code block to be registered
$positionintThe position at which the JS script tag should be inserted in a page. The possible values are: - POS_HEAD: in the head section - POS_BEGIN: at the beginning of the body section - POS_END: at the end of the body section - POS_LOAD: enclosed within a window load event listener. - POS_READY: enclosed within a DOMContentLoaded event listener. This is the default value.
$keystring|nullThe key that identifies the JS code block. If null, it will use $js as the key. If two JS code blocks are registered with the same key, the latter will overwrite the former.

Returns

mixed

public function registerJsFile(string $url, yii\web\RegisterJsFileOptions $options = [], string|null $key = null): mixed

Registers a JS file.

This method should be used for simple registration of JS files. If you want to use features of AssetManager like appending timestamps to the URL and file publishing options, use AssetBundle and registerAssetBundle() instead.

Parameters

ParameterTypeDescription
$urlstringThe JS file to be registered.
$optionsyii\web\RegisterJsFileOptionsThe HTML attributes for the script tag. The following options are specially handled and are not treated as HTML attributes: - depends: array, specifies the names of the asset bundles that this JS file depends on. - position: specifies where the JS script tag should be inserted in a page. The possible values are: * POS_HEAD: in the head section * POS_BEGIN: at the beginning of the body section * POS_END: at the end of the body section. This is the default value. - appendTimestamp: bool whether to append a timestamp to the URL. Please refer to Html::jsFile() for other supported options.
$keystring|nullThe key that identifies the JS script file. If null, it will use $url as the key. If two JS files are registered with the same key at the same position, the latter will overwrite the former. Note that position option takes precedence, thus files registered with the same key, but different position option will not override each other.

Returns

mixed

Throws

public function registerJsVar(string $name, array|string $value, int $position = \self::POS_HEAD): mixed

Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated variable names.

Parameters

ParameterTypeDescription
$namestringName of the variable
$valuearray|stringValue of the variable
$positionintThe position in a page at which the JavaScript variable should be inserted. The possible values are: - POS_HEAD: in the head section. This is the default value. - POS_BEGIN: at the beginning of the body section. - POS_END: at the end of the body section. - POS_LOAD: enclosed within a window load event listener. - POS_READY: enclosed within a DOMContentLoaded event listener.

Returns

mixed

Since

2.0.14

public function registerLinkTag(array $options, string|null $key = null): mixed

Registers a link tag.

For example, a link tag for a custom favicon can be added like the following:

$view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);

which will result in the following HTML: <link rel="icon" type="image/png" href="/myicon.png">.

Note: To register link tags for CSS stylesheets, use registerCssFile() instead, which has more options for this kind of link tag.

Parameters

ParameterTypeDescription
$optionsarrayThe HTML attributes for the link tag.
$keystring|nullThe key that identifies the link tag. If two link tags are registered with the same key, the latter will overwrite the former. If this is null, the new link tag will be appended to the existing ones.

Returns

mixed

public function registerMetaTag(array $options, string|null $key = null): mixed

Registers a meta tag.

For example, a description meta tag can be added like the following:

$view->registerMetaTag([
'name' => 'description',
'content' => 'This website is about funny raccoons.'
]);

will result in the meta tag <meta name="description" content="This website is about funny raccoons.">.

Parameters

ParameterTypeDescription
$optionsarrayThe HTML attributes for the meta tag.
$keystring|nullThe key that identifies the meta tag. If two meta tags are registered with the same key, the latter will overwrite the former. If this is null, the new meta tag will be appended to the existing ones.

Returns

mixed

public function renderAjax(string $view, array $params = [], object|null $context = null): string

Renders a view in response to an AJAX request.

This method is similar to render() except that it will surround the view being rendered with the calls of beginPage(), head(), beginBody(), endBody() and endPage(). By doing so, the method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the view.

Parameters

ParameterTypeDescription
$viewstringThe view name. Please refer to render() on how to specify this parameter.
$paramsarrayThe parameters (name-value pairs) that will be extracted and made available in the view file.
$contextobject|nullThe context that the view should use for rendering the view. If null, existing $context will be used.

Returns

string: The rendering result

See also

public function setAssetManager(yii\web\AssetManager $value): mixed

Sets the asset manager.

Parameters

ParameterTypeDescription
$valueAssetManagerThe asset manager

Returns

mixed

protected function registerAssetFiles(string $name): mixed

Registers all files provided by an asset bundle including depending bundles files.

Removes a bundle from $assetBundles once files are registered.

Parameters

ParameterTypeDescription
$namestringName of the bundle to register

Returns

mixed

protected function renderBodyBeginHtml(): string

Renders the content to be inserted at the beginning of the body section.

The content is rendered using the registered JS code blocks and files.

Returns

string: The rendered content

protected function renderBodyEndHtml(bool $ajaxMode): string

Renders the content to be inserted at the end of the body section.

The content is rendered using the registered JS code blocks and files.

Parameters

ParameterTypeDescription
$ajaxModeboolWhether the view is rendering in AJAX mode. If true, the JS scripts registered at POS_READY and POS_LOAD positions will be rendered at the end of the view like normal scripts.

Returns

string: The rendered content

protected function renderHeadHtml(): string

Renders the content to be inserted in the head section.

The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.

Returns

string: The rendered content

protected function wrapLoadScript(string $script): string

Wraps script content for POS_LOAD position.

Parameters

ParameterTypeDescription
$scriptstringThe script content to wrap

Returns

string: The wrapped script

Since

22.0

protected function wrapReadyScript(string $script): string

Wraps script content for POS_READY position.

Parameters

ParameterTypeDescription
$scriptstringThe script content to wrap

Returns

string: The wrapped script

Since

22.0