View, the V in the MVC triad. View interacts with Helpers and view variables passed in from the controller to render the results of the controller action. Often this is HTML, but can also take the form of JSON, XML, PDF's or streaming files.
CakePHP uses a two-step-view pattern. This means that the template content is rendered first, and then inserted into the selected layout. This also means you can pass data from the template to the layout using $this->set()
View class supports using plugins as themes. You can set
public function beforeRender(\Cake\Event\Event $event)
{
$this->viewBuilder()->setTheme('SuperHot');
} in your Controller to use plugin SuperHot as a theme. Eg. If current action is PostsController::index() then View class will look for template file plugins/SuperHot/Template/Posts/index.ctp. If a theme template is not found for the current action the default app template file is used.
string
NAME_ELEMENT 'Element' string
NAME_TEMPLATE 'Template' string
TYPE_ELEMENT 'element' string
TYPE_LAYOUT 'layout' string
TYPE_TEMPLATE 'view' string
TYPE_VIEW 'view' $Blocks protected $_current protected string$_currentType protected stringCurrently rendering an element. Used for finding parent fragments for elements.
$_ext protected string$_helpers protected $_parents protected array$_passedVars protected array$_paths protected array$_pathsForPlugin protected array$_stack protected array$_viewBlockClass protected string$autoLayout protected booleanTurns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
$elementCache protected stringThe Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
$hasRendered public boolean$helpers protected array$layout protected stringThe name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
$layoutPath protected string$name protected string$passedArgs public array$plugin protected string|null$request protected An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
$response protected $subDir protected stringSub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/
$template protected stringThe name of the template file to render. The name specified is the filename in /src/Template/
$templatePath protected string$theme protected string|null$uuids public array$Blocks public $Breadcrumbs public $Flash public $Form public $Html public $Number public $Paginator public $Rss public $Session public $Text public $Time public $Url public $view public string$viewPath public stringFind all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
Set the content for a block. This will overwrite any existing content.
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.
Fetch the content for a block. If a block is empty or undefined '' will be returned.
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
Get the name of the template file to render. The name specified is the filename in /src/Template/
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
HelperRegistry::load() to load the helper Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.
Reset the content for a block. This will overwrite any existing content.
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
Set the name of the template file to render. The name specified is the filename in /src/Template/
Get/set the name of the template file to render. The name specified is the filename in /src/Template/
__construct( Cake\Http\ServerRequest $request = null , Cake\Http\Response $response = null , Cake\Event\EventManager $eventManager = null , array $viewOptions = [] )
Constructor
Cake\Http\ServerRequest $request optional null Cake\Http\Response $response optional null Cake\Event\EventManager $eventManager optional null $viewOptions optional [] View options. See View::$_passedVars for list of options which get set as class properties.
__get( string $name )
Magic accessor for helpers.
$name __set( string $name , mixed $value )
Magic setter for deprecated properties.
$name $value _checkFilePath( string $file , string $path )
Check that a view file path does not go outside of the defined template paths.
Only paths that contain .. will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.
$file $path _elementCache( string $name , array $data , array $options )
Generate the cache configuration options for an element.
$name $data $options _evaluate( string $viewFile , array $dataForView )
Sandbox method to evaluate a template / view script in.
$viewFile $dataForView _getElementFileName( string $name , boolean $pluginCheck = true )
Finds an element filename, returns false on failure.
$name $pluginCheck optional true _getLayoutFileName( string|null $name = null )
Returns layout filename for this template as a string.
$name optional null Cake\View\Exception\MissingLayoutException_getSubPaths( string $basePath )
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
$basePath _getViewFileName( string|null $name = null )
Returns filename of given action's template file (.ctp) as a string. CamelCased action names will be under_scored by default. This means that you can have LongActionNames that refer to long_action_names.ctp views. You can change the inflection rule by overriding _inflectViewFileName.
$name optional null Cake\View\Exception\MissingTemplateException_inflectViewFileName( string $name )
Change the name of a view template file into underscored format.
$name _paths( string|null $plugin = null , boolean $cached = true )
Return all possible paths to find view files in order
$plugin optional null $cached optional true _render( string $viewFile , array $data = [] )
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
$viewFile $data optional [] Data to include in rendered view. If empty the current View::$viewVars will be used.
_renderElement( string $file , array $data , array $options )
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
$file $data $options append( string $name , mixed $value = null )
Append to an existing or new block.
Appending to a new block will create the block.
$name $value optional null The content for the block. Value will be type cast to string.
assign( string $name , mixed $value )
Set the content for a block. This will overwrite any existing content.
$name $value The content for the block. Value will be type cast to string.
autoLayout( boolean|null $autoLayout = null )
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
$autoLayout optional null blocks( )
Get the names of all the existing blocks.
cache( callable $block , array $options = [] )
Create a cached block of view logic.
This allows you to cache a block of view output into the cache defined in elementCache.
This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.
$block $options optional [] disableAutoLayout( )
Turns off CakePHP's conventional mode of applying layout files.
Layouts will not be automatically applied to rendered views.
element( string $name , array $data = [] , array $options = [] )
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the cache option.
$name Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
$data optional [] $options optional [] Array of options. Possible keys are: - cache - Can either be true, to enable caching using the config in View::$elementCache. Or an array If an array, the following keys can be used: - config - Used to store the cached element in a custom cache configuration. - key - Used to define the key used in the Cache::write(). It will be prefixed with element_ - callbacks - Set to true to fire beforeRender and afterRender helper callbacks for this element. Defaults to false. - ignoreMissing - Used to allow missing elements. Set to true to not throw exceptions. - plugin - setting to false will force to use the application's element from plugin templates, when the plugin has element with same name. Defaults to true
Cake\View\Exception\MissingElementExceptionWhen an element is missing and ignoreMissing is false.
elementExists( string $name )
Checks if an element exists
$name Name of template file in the /src/Template/Element/ folder, or MyPlugin.template to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
enableAutoLayout( boolean $enable = true )
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
$enable optional true end( )
End a capturing block. The compliment to View::start()
exists( string $name )
Check if a block exists
$name extend( string $name )
Provides template or element extension/inheritance. Views can extends a parent view and populate blocks in the parent template.
$name fetch( string $name , string $default = '' )
Fetch the content for a block. If a block is empty or undefined '' will be returned.
$name $default optional '' get( string $var , mixed $default = null )
Returns the contents of the given View variable.
$var $default optional null getLayout( )
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
getName( )
Returns the View's controller name.
getRequest( )
Gets the request instance.
Cake\Http\ServerRequestgetResponse( )
Gets the response instance.
Cake\Http\ResponsegetSubDir( )
Get sub-directory for this template files.
getTemplate( )
Get the name of the template file to render. The name specified is the filename in /src/Template/
getVars( )
Returns a list of variables available in the current View context
helpers( )
Get the helper registry in use by this View class.
Cake\View\HelperRegistryinitialize( )
Initialization hook method.
Properties like $helpers etc. cannot be initialized statically in your custom view class as they are overwritten by values from controller in constructor. So this method allows you to manipulate them as required after view instance is constructed.
isAutoLayoutEnabled( )
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
layout( string|null $name = null )
Get/set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
$name optional null layoutPath( string|null $path = null )
Get/set path for layout files.
$path optional null loadHelper( string $name , array $config = [] )
Loads a helper. Delegates to the HelperRegistry::load() to load the helper
$name $config optional [] Cake\View\HelperloadHelpers( )
Interact with the HelperRegistry to load all the helpers.
pluginSplit( string $name , boolean $fallback = true )
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
$name $fallback optional true prepend( string $name , mixed $value )
Prepend to an existing or new block.
Prepending to a new block will create the block.
$name $value The content for the block. Value will be type cast to string.
render( string|false|null $view = null , string|null $layout = null )
Renders view for given template file and layout.
Render triggers helper callbacks, which are fired before and after the template are rendered, as well as before and after the layout. The helper callbacks are called:
beforeRenderafterRenderbeforeLayoutafterLayoutIf View::$autoRender is false and no $layout is provided, the template will be returned bare.
Template and layout names can point to plugin templates/layouts. Using the Plugin.template syntax a plugin template/layout can be used instead of the app ones. If the chosen plugin is not found the template will be located along the regular view path cascade.
$view optional null $layout optional null Cake\Core\Exception\ExceptionrenderLayout( string $content , string|null $layout = null )
Renders a layout. Returns output from _render(). Returns false on error. Several variables are created for use in layout.
$content $layout optional null Cake\Core\Exception\Exceptionreset( string $name )
Reset the content for a block. This will overwrite any existing content.
$name setElementCache( string $elementCache )
Set The cache configuration View will use to store cached elements
$elementCache setLayout( string $name )
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
$name setLayoutPath( string $path )
Set path for layout files.
$path setPlugin( string $name )
Sets the plugin name.
$name setRequest( Cake\Http\ServerRequest $request )
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
Cake\Http\ServerRequest $request setResponse( Cake\Http\Response $response )
Sets the response instance.
Cake\Http\Response $response setSubDir( string $subDir )
Set sub-directory for this template files.
$subDir setTemplate( string $name )
Set the name of the template file to render. The name specified is the filename in /src/Template/
$name setTemplatePath( string $path )
Set path for templates files.
$path setTheme( string|null $theme )
Set the view theme to use.
$theme start( string $name )
Start capturing output for a 'block'
You can use start on a block multiple times to append or prepend content in a capture mode.
// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();
// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end(); $name template( string|null $name = null )
Get/set the name of the template file to render. The name specified is the filename in /src/Template/
$name optional null templatePath( string|null $path = null )
Get/set path for templates files.
$path optional null theme( string|null $theme = null )
The view theme to use.
$theme optional null uuid( string $object , string $url )
Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
$object $url _createCell( string $className , string $action , string $plugin , array $options )
Create and configure the cell instance.
$className $action $plugin $options Cake\View\Cellcell( string $cell , array $data = [] , array $options = [] )
Renders the given cell.
Example:
// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);
// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]); The display action will be used by default when no action is provided:
// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud'); Cells are not rendered until they are echoed.
$cell You must indicate cell name, and optionally a cell action. e.g.: TagCloud::smallList will invoke View\Cell\TagCloudCell::smallList(), display action will be invoked by default when none is provided.
$data optional [] Additional arguments for cell method. e.g.: cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2']) maps to View\Cell\TagCloud::smallList(v1, v2)
$options optional [] Cake\View\CellCake\View\Exception\MissingCellExceptiondispatchEvent( string $name , array|null $data = null , object|null $subject = null )
Wrapper for creating and dispatching events.
Returns a dispatched event.
$name $data optional null Any value you wish to be transported with this event to it can be read by listeners.
$subject optional null The object that this event applies to ($this by default).
Cake\Event\EventeventManager( Cake\Event\EventManager $eventManager = null )
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Cake\Event\EventManager $eventManager optional null Cake\Event\EventManagergetEventManager( )
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Cake\Event\EventManagersetEventManager( Cake\Event\EventManager $eventManager )
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Cake\Event\EventManager $eventManager log( mixed $msg , integer|string $level = LogLevel::ERROR , string|array $context = [] )
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
$msg $level optional LogLevel::ERROR $context optional [] requestAction( string|array $url , array $extra = [] )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
A basic example getting the return value of the controller action:
$variables = $this->requestAction('/articles/popular'); A basic example of request action to fetch a rendered page without the layout.
$viewHtml = $this->requestAction('/articles/popular', ['return']); You can also pass the URL as an array:
$vars = $this->requestAction(['controller' => 'articles', 'action' => 'popular']);
You can pass POST, GET, COOKIE and other data into the request using the appropriate keys. Cookies can be passed using the cookies key. Get parameters can be set with query and post data can be sent using the post key.
$vars = $this->requestAction('/articles/popular', [
'query' => ['page' => 1],
'cookies' => ['remember_me' => 1],
]); By default actions dispatched with this method will use the global $_SERVER and $_ENV values. If you want to override those values for a request action, you can specify the values:
$vars = $this->requestAction('/articles/popular', [
'environment' => ['CONTENT_TYPE' => 'application/json']
]); By default actions dispatched with this method will use the standard session object. If you want a particular session instance to be used, you need to specify it.
$vars = $this->requestAction('/articles/popular', [
'session' => new Session($someSessionConfig)
]); $url String or array-based url. Unlike other url arrays in CakePHP, this url will not automatically handle passed arguments in the $url parameter.
$extra optional [] if array includes the key "return" it sets the autoRender to true. Can also be used to submit GET/POST data, and passed arguments.
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
createView( string|null $viewClass = null )
Constructs the view class instance based on the current configuration.
$viewClass optional null Cake\View\ViewCake\View\Exception\MissingViewExceptionset( string|array $name , mixed $value = null )
Saves a variable or an associative array of variables for use inside a template.
$name $value optional null Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.
viewBuilder( )
Get the view builder being used.
Cake\View\ViewBuilderviewOptions( string|array|null $options = null , boolean $merge = true )
Get/Set valid view options in the object's _validViewOptions property. The property is created as an empty array if it is not set. If called without any parameters it will return the current list of valid view options. See createView().
$options optional null $merge optional true Whether to merge with or override existing valid View options. Defaults to true.
getEventManager() |
protected string
The currently rendering view file. Used for resolving parent files.
protected string
Currently rendering an element. Used for finding parent fragments for elements.
''
protected array
List of variables to collect from the associated controller.
[
'viewVars', 'autoLayout', 'helpers', 'template', 'layout', 'name', 'theme',
'layoutPath', 'templatePath', 'plugin', 'passedArgs'
] protected array
Content stack, used for nested templates that all use View::extend();
[]
protected boolean
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
true
protected string
The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
'default'
public boolean
True when the view has been rendered.
false
protected string
The name of the layout file to render the template inside of. The name specified is the filename of the layout in /src/Template/Layout without the .ctp extension.
'default'
protected string
The name of the layouts subfolder containing layouts for this View.
public array
Current passed params. Passed to View from the creating Controller for convenience.
$this->request->getParam('pass') instead.[]
protected Cake\Http\ServerRequest
An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
protected string
Sub-directory for this template file. This is often used for extension based routing. Eg. With an xml extension, $subDir would be xml/
''
protected string
The name of the template file to render. The name specified is the filename in /src/Template/
public array
List of generated DOM UUIDs.
[]
public Cake\View\ViewBlock
public Cake\View\Helper\FlashHelper
public Cake\View\Helper\FormHelper
public Cake\View\Helper\HtmlHelper
public Cake\View\Helper\RssHelper
public Cake\View\Helper\TextHelper
public Cake\View\Helper\TimeHelper
public Cake\View\Helper\UrlHelper
public string
public string
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/3.8/class-Cake.View.View.html