Skip to content

View

Type
Class
Namespace
craft\web
Inherits
craft\web\View » yii\web\View » yii\base\View » yii\base\Component » yii\base\BaseObject
Implements
yii\base\Configurable, yii\base\DynamicContentAwareInterface
Since
3.0.0

View source

Public Properties

PropertyDescription
allowEvalboolean – Whether to allow evaluateDynamicContent() to be called.
assetBundlesyii\web\AssetBundle – List of the registered asset bundles.
assetManageryii\web\AssetManager – The asset manager.
behaviorsyii\base\Behavior – List of behaviors attached to this component.
blocksarray – A list of named output blocks.
bodyHtmlstring – the content to be inserted at the end of the body section
contextyii\base\ViewContextInterface – The context under which the renderFile() method is being invoked.
cpTemplateRootsarray – any registered control panel template roots
cssarray – The registered CSS code blocks.
cssFilesarray – The registered CSS files.
defaultExtensionstring – The default view file extension.
deltaNamesstring[]
dynamicContentsyii\base\DynamicContentAwareInterface – Class instances supporting dynamic contents.
dynamicPlaceholdersarray – A list of placeholders.
headHtmlstring – the content to be inserted in the head section
initialDeltaValuesarray
isDeltaRegistrationActiveboolean
isRenderingPageTemplateboolean – whether a page template is currently being rendered
isRenderingTemplateboolean – whether a template is currently being rendered
jsarray – The registered JS code blocks
jsFilesarray – The registered JS files.
linkTagsarray – The registered link tags.
metaTagsarray – The registered meta tags.
minifyCssboolean – Whether to minify CSS registered with registerCss()
minifyJsboolean – Whether to minify JS registered with registerJs()
modifiedDeltaNamesstring[]
namespacestring, null – the active namespace
paramsarray – Custom parameters that are shared among view templates.
registeredAssetBundlesstring[] – the asset bundle names that should be marked as already registered
registeredJsFilesstring[] – the JS files that should be marked as already registered
renderersarray, null – A list of available renderers indexed by their corresponding supported file extensions.
scriptOptionsarray – The script tag options.
siteTemplateRootsarray – any registered site template roots
templateModestring – the current template mode (either site or cp)
templatesPathstring – the base path that templates should be found in
themeyii\base\Theme, array, string, null – The theme object or the configuration for creating the theme object.
titlestring – The page title
twigcraft\web\twig\Environment – the Twig environment
viewFilestring, boolean – The view file currently being rendered.

allowEval

Type
boolean
Default value
false
Since
3.5.0

Whether to allow evaluateDynamicContent() to be called.

WARNING

Don’t enable this unless you have a very good reason to.

View source

bodyHtml

Type
string
Default value
null

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

View source

cpTemplateRoots

Type
array
Default value
null

any registered control panel template roots

View source

deltaNames

Type
string[]
Default value
null
Access
Read-only
Since
3.4.0

View source

headHtml

Type
string
Default value
null

the content to be inserted in the head section

View source

initialDeltaValues

Type
array
Default value
null
Access
Read-only
Since
3.7.0

View source

isDeltaRegistrationActive

Type
boolean
Default value
null
Since
3.4.0

View source

isRenderingPageTemplate

Type
boolean
Default value
null

whether a page template is currently being rendered

View source

isRenderingTemplate

Type
boolean
Default value
null

whether a template is currently being rendered

View source

minifyCss

DEPRECATED

Deprecated in 3.6.0.

Type
boolean
Default value
false
Since
3.4.0

Whether to minify CSS registered with registerCss()

View source

minifyJs

DEPRECATED

Deprecated in 3.6.0

Type
boolean
Default value
false
Since
3.4.0

Whether to minify JS registered with registerJs()

View source

modifiedDeltaNames

Type
string[]
Default value
null
Access
Read-only
Since
4.10.1

View source

namespace

Type
string, null
Default value
null

the active namespace

View source

registeredAssetBundles

Type
string[]
Default value
null

the asset bundle names that should be marked as already registered

View source

registeredJsFiles

Type
string[]
Default value
null

the JS files that should be marked as already registered

View source

siteTemplateRoots

Type
array
Default value
null

any registered site template roots

View source

templateMode

Type
string
Default value
null

the current template mode (either site or cp)

View source

templatesPath

Type
string
Default value
null

the base path that templates should be found in

View source

twig

Type
craft\web\twig\Environment
Default value
null

the Twig environment

View source

Protected Properties

PropertyDescription
isPageEndedboolean

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()Constructor.
__get()Returns the value of a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__unset()Sets a component property to be null.
addDynamicPlaceholder()Adds a placeholder for dynamic content.
afterRender()This method is invoked right after renderFile() renders a view file.
afterRenderPageTemplate()Performs actions after a page template is rendered.
afterRenderTemplate()Performs actions after a template is rendered.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
beforeRender()This method is invoked right before renderFile() renders a view file.
beforeRenderPageTemplate()Performs actions before a page template is rendered.
beforeRenderTemplate()Performs actions before a template is rendered.
beginBlock()Begins recording a block.
beginBody()Marks the beginning of an HTML body section.
beginCache()Begins fragment caching.
beginContent()Begins the rendering of content that is to be decorated by the specified view.
beginPage()Marks the beginning of a page.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
clear()Clears up the registered meta tags, link tags, css/js scripts and files.
clearAssetBundleBuffer()Clears and ends a buffer started via startAssetBundleBuffer(), returning any asset bundles that were registered while the buffer was active.
clearCssBuffer()Clears and ends a buffer started via startCssBuffer(), returning any <style> tags that were registered while the buffer was active.
clearCssFileBuffer()Clears and ends a buffer started via startCssFileBuffer(), returning any <link rel="stylesheet"> tags that were registered while the buffer was active.
clearHtmlBuffer()Clears and ends a buffer started via startHtmlBuffer(), returning any html tags that were registered while the buffer was active.
clearJsBuffer()Clears and ends a buffer started via startJsBuffer(), returning any JavaScript code that was registered while the buffer was active.
clearJsFileBuffer()Clears and ends a buffer started via startJsFileBuffer(), returning any <script> tags that were registered while the buffer was active.
clearMetaTagBuffer()Clears and ends a buffer started via startMetaTagBuffer(), returning any <meta> tags that were registered while the buffer was active.
clearScriptBuffer()Clears and ends a buffer started via startScriptBuffer(), returning any <script> tags that were registered while the buffer was active.
createTwig()Creates a new Twig environment.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
doesTemplateExist()Returns whether a template exists.
endBlock()Ends recording a block.
endBody()Marks the ending of an HTML body section.
endCache()Ends fragment caching.
endContent()Ends the rendering of content.
endPage()Marks the ending of an HTML page.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
evaluateDynamicContent()Evaluates the given PHP statements.
formatInputId()Formats an ID out of an input name.
getAssetManager()Registers the asset manager being used by this view object.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getBodyHtml()Returns the content to be inserted at the end of the body section.
getCpTemplateRoots()Returns any registered control panel template roots.
getDeltaNames()Returns all the registered delta input names.
getDynamicContents()Returns a list of currently active dynamic content class instances.
getDynamicPlaceholders()Returns a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.
getHeadHtml()Returns the content to be inserted in the head section.
getInitialDeltaValues()Returns the initial values of delta inputs.
getIsDeltaRegistrationActive()Returns whether delta input name registration is currently active
getIsRenderingPageTemplate()Returns whether a page template is currently being rendered.
getIsRenderingTemplate()Returns whether a template is currently being rendered.
getModifiedDeltaNames()Returns all the registered delta input names that should be considered modified.
getNamespace()Returns the active namespace.
getSiteTemplateRoots()Returns any registered site template roots.
getTemplateMode()Returns the current template mode (either site or cp).
getTemplatesPath()Returns the base path that templates should be found in.
getTwig()Returns the Twig environment.
getViewFile()
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined for this component.
head()Marks the position of an HTML head section.
hook()Queues up a method to be called by a given template hook.
init()Initializes the view component.
invokeHook()Invokes a template hook.
namespaceInputId()Namespaces an input ID.
namespaceInputName()Namespaces an input name.
namespaceInputs()Renames HTML input names so they belong to a namespace.
normalizeObjectTemplate()Normalizes an object template for renderObjectTemplate().
off()Detaches an existing event handler from this component.
on()Attaches an event handler to an event.
popDynamicContent()Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class instances.
pushDynamicContent()Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class instances.
registerAssetBundle()Registers the named asset bundle.
registerCsrfMetaTags()Registers CSRF meta tags.
registerCss()Registers a CSS code block.
registerCssFile()Registers a CSS file.
registerDeltaName()Registers a delta input name.
registerHtml()Registers arbitrary HTML to be injected into the final page response.
registerJs()Registers a JS code block.
registerJsFile()Registers a JS file.
registerJsVar()Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated variable names.
registerJsWithVars()Registers JavaScript code with the given variables, pre-JSON-encoded.
registerLinkTag()Registers a link tag.
registerMetaTag()Registers a meta tag.
registerScript()Registers a generic <script> code block.
registerTranslations()Translates messages for a given translation category, so they will be available for Craft.t() calls in the control panel.
registerTwigExtension()Registers a new Twig extension, which will be added on existing environments and queued up for future environments.
render()Renders a view.
renderAjax()Renders a view in response to an AJAX request.
renderDynamic()Renders dynamic content returned by the given PHP statements.
renderFile()Renders a view file.
renderObjectTemplate()Renders an object template.
renderPageTemplate()Renders a Twig template that represents an entire web page.
renderPhpFile()Renders a view file as a PHP script.
renderString()Renders a template defined in a string.
renderTemplate()Renders a Twig template.
resolveTemplate()Finds a template on the file system and returns its path.
setAssetManager()Sets the asset manager.
setDynamicPlaceholders()Sets a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.
setInitialDeltaValue()Sets the initial value of a delta input name.
setIsDeltaRegistrationActive()Sets whether delta input name registration is active.
setNamespace()Sets the active namespace.
setRegisteredAssetBundles()Sets the asset bundle names that should be marked as already registered.
setRegisteredJsFiles()Sets the JS files that should be marked as already registered.
setTemplateMode()Sets the current template mode.
setTemplatesPath()Sets the base path that templates should be found in.
startAssetBundleBuffer()Starts a buffer for any asset bundles registered with registerAssetBundle().
startCssBuffer()Starts a buffer for any <style> tags registered with registerCss().
startCssFileBuffer()Starts a buffer for any <link> tags registered with registerCssFile().
startHtmlBuffer()Starts a buffer for any html tags registered with registerHtml().
startJsBuffer()Starts a buffer for any JavaScript code registered with registerJs().
startJsFileBuffer()Starts a buffer for any <script> tags registered with registerJsFile().
startMetaTagBuffer()Starts a buffer for any <meta> tags registered with registerMetaTag().
startScriptBuffer()Starts a buffer for any <script> tags registered with registerScript().
trigger()Triggers an event.

afterRenderPageTemplate()

Performs actions after a page template is rendered.

View source

Arguments

  • $template (string) – The name of the template that was rendered
  • $variables (array) – The variables that were available to the template
  • $templateMode (string) – The template mode that was used when rendering the template
  • $output (string) – The template’s rendering result

afterRenderTemplate()

Performs actions after a template is rendered.

View source

Arguments

  • $template (string) – The name of the template that was rendered
  • $variables (array) – The variables that were available to the template
  • $templateMode (string) – The template mode that was used when rendering the template
  • $output (string) – The template’s rendering result

beforeRenderPageTemplate()

Performs actions before a page template is rendered.

View source

Arguments

  • $template (string) – The name of the template to render
  • $variables (array) – The variables that should be available to the template
  • $templateMode (string) – The template mode to use when rendering the template

Returns

boolean – Whether the template should be rendered

beforeRenderTemplate()

Performs actions before a template is rendered.

View source

Arguments

  • $template (string) – The name of the template to render
  • $variables (array) – The variables that should be available to the template
  • $templateMode (string) – The template mode to use when rendering the template

Returns

boolean – Whether the template should be rendered

clearAssetBundleBuffer()

Since
4.11.0

Clears and ends a buffer started via startAssetBundleBuffer(), returning any asset bundles that were registered while the buffer was active.

See also startAssetBundleBuffer()View source

Returns

array, false – The asset bundles that were registered while the buffer was active, or false if there wasn’t an active buffer.

clearCssBuffer()

Since
3.7.0

Clears and ends a buffer started via startCssBuffer(), returning any <style> tags that were registered while the buffer was active.

See also startCssBuffer()View source

Returns

array, false – The <style> tags that were registered while the buffer was active, or false if there wasn’t an active buffer.

clearCssFileBuffer()

Since
4.0.0

Clears and ends a buffer started via startCssFileBuffer(), returning any <link rel="stylesheet"> tags that were registered while the buffer was active.

See also startCssFileBuffer()View source

Returns

array, false – The <link rel="stylesheet"> tags that were registered while the buffer was active, or false if there wasn’t an active buffer.

clearHtmlBuffer()

Since
4.3.0

Clears and ends a buffer started via startHtmlBuffer(), returning any html tags that were registered while the buffer was active.

View source

Returns

array, false – The html that was registered while the buffer was active or false if there wasn't an active buffer.

clearJsBuffer()

Clears and ends a buffer started via startJsBuffer(), returning any JavaScript code that was registered while the buffer was active.

See also startJsBuffer()View source

Arguments

  • $scriptTag (boolean) – Whether the returned JavaScript code should be wrapped in a <script> tag.
  • $combine (boolean) – Whether the JavaScript code should be returned in a combined blob. (Position and key info will be lost.)

Returns

string, array, false – The JavaScript code that was registered while the buffer was active, or false if there wasn’t an active buffer.

clearJsFileBuffer()

Since
4.0.0

Clears and ends a buffer started via startJsFileBuffer(), returning any <script> tags that were registered while the buffer was active.

See also startJsFileBuffer()View source

Returns

array, false – The <script> tags that were registered while the buffer was active (indexed by position), or false if there wasn’t an active buffer.

clearMetaTagBuffer()

Since
4.5.8

Clears and ends a buffer started via startMetaTagBuffer(), returning any <meta> tags that were registered while the buffer was active.

See also startMetaTagBuffer()View source

Returns

array, false – The <meta> tags that were registered while the buffer was active (indexed by position), or false if there wasn’t an active buffer.

clearScriptBuffer()

Since
3.7.0

Clears and ends a buffer started via startScriptBuffer(), returning any <script> tags that were registered while the buffer was active.

See also startScriptBuffer()View source

Returns

array, false – The <script> tags that were registered while the buffer was active, or false if there wasn’t an active buffer.

createTwig()

Creates a new Twig environment.

View source

Returns

craft\web\twig\Environment

doesTemplateExist()

Returns whether a template exists.

Internally, this will just call resolveTemplate() with the given template name, and return whether that method found anything.

View source

Arguments

  • $name (string) – The name of the template.
  • $templateMode (string, null) – The template mode to use.
  • $publicOnly (boolean) – Whether to only look for public templates (template paths that don’t start with the private template trigger).

Returns

boolean – Whether the template exists.

Throws

endBody()

Marks the ending of an HTML body section.

View source

endPage()

Marks the ending of an HTML page.

View source

Arguments

  • $ajaxMode (boolean) – Whether 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.

evaluateDynamicContent()

Evaluates the given PHP statements.

This method is mainly used internally to implement dynamic content feature.

View source

Arguments

  • $statements (string) – The PHP statements to be evaluated.

Returns

mixed – The return value of the PHP statements.

Throws

formatInputId()

DEPRECATED

Deprecated in 3.5.0. Use craft\helpers\Html::id() instead.

Formats an ID out of an input name.

This method takes a given input name and returns a valid ID based on it. For example, if given the following input name: foo[bar][title] the following ID would be returned: foo-bar-title

View source

Arguments

  • $inputName (string) – The input name.

Returns

string – The input ID.

getBodyHtml()

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

This includes:

View source

Arguments

  • $clear (boolean) – Whether the content should be cleared from the queue (default is true)

Returns

string – The rendered content

getCpTemplateRoots()

Returns any registered control panel template roots.

View source

Returns

array

getDeltaNames()

Since
3.4.0

Returns all the registered delta input names.

See also registerDeltaName()View source

Returns

string[]

getHeadHtml()

Returns the content to be inserted in the head section.

This includes:

View source

Arguments

  • $clear (boolean) – Whether the content should be cleared from the queue (default is true)

Returns

string – The rendered content

getInitialDeltaValues()

Since
3.7.0

Returns the initial values of delta inputs.

See also setInitialDeltaValue()View source

Returns

array

getIsDeltaRegistrationActive()

Since
3.4.0

Returns whether delta input name registration is currently active

See also registerDeltaName()View source

Returns

boolean

getIsRenderingPageTemplate()

Returns whether a page template is currently being rendered.

View source

Returns

boolean – Whether a page template is currently being rendered.

getIsRenderingTemplate()

Returns whether a template is currently being rendered.

View source

Returns

boolean – Whether a template is currently being rendered.

getModifiedDeltaNames()

Since
4.10.1

Returns all the registered delta input names that should be considered modified.

See also registerDeltaName()View source

Returns

string[]

getNamespace()

Returns the active namespace.

This is the default namespaces that will be used when namespaceInputs(), namespaceInputName(), and namespaceInputId() are called, if their $namespace arguments are null.

View source

Returns

string, null – The namespace.

getSiteTemplateRoots()

Returns any registered site template roots.

View source

Returns

array

getTemplateMode()

Returns the current template mode (either site or cp).

View source

Returns

string – Either site or cp.

getTemplatesPath()

Returns the base path that templates should be found in.

View source

Returns

string

getTwig()

Returns the Twig environment.

View source

Returns

craft\web\twig\Environment

hook()

Queues up a method to be called by a given template hook.

For example, if you place this in your plugin’s init() method:

php
Craft::$app->view->hook('myAwesomeHook', function(&$context) {
    $context['foo'] = 'bar';
    return 'Hey!';
});

you would then be able to add this to any template:

twig
{% hook "myAwesomeHook" %}

When the hook tag gets invoked, your template hook function will get called. The $context argument will be the current Twig context array, which you’re free to manipulate. Any changes you make to it will be available to the template following the tag. Whatever your template hook function returns will be output in place of the tag in the template as well.

If you want to prevent additional hook methods from getting triggered, add a second $handled argument to your callback method, which should be passed by reference, and then set it to true within the method.

php
Craft::$app->view->hook('myAwesomeHook', function(&$context, &$handled) {
    $context['foo'] = 'bar';
    $handled = true;
    return 'Hey!';
});

View source

Arguments

  • $hook (string) – The hook name.
  • $method (callable) – The callback function.
  • $append (boolean) – Whether to append the method handler to the end of the existing method list for the hook. If false, the method will be inserted at the beginning of the existing method list.

init()

Initializes the view component.

View source

invokeHook()

Invokes a template hook.

This is called by \craft\web\HookNode.

View source

Arguments

  • $hook (string) – The hook name.
  • $context (array) – The current template context.

Returns

string – Whatever the hooks returned.

namespaceInputId()

Namespaces an input ID.

This method applies the same namespacing treatment that namespaceInputs() does to id= attributes, but only to a single value, which is passed directly into this method.

View source

Arguments

Returns

string – The namespaced input ID.

namespaceInputName()

Namespaces an input name.

This method applies the same namespacing treatment that namespaceInputs() does to name= attributes, but only to a single value, which is passed directly into this method.

View source

Arguments

Returns

string – The namespaced input name.

namespaceInputs()

Renames HTML input names so they belong to a namespace.

This method will go through the passed-in $html looking for name= attributes, and renaming their values such that they will live within the passed-in $namespace (or the active namespace). By default, any id=, for=, list=, data-target=, data-reverse-target=, and data-target-prefix= attributes will get namespaced as well, by prepending the namespace and a dash to their values. For example, the following HTML:

html
<label for="title">Title</label>
<input type="text" name="title" id="title">

would become this, if it were namespaced with “foo”:

html
<label for="foo-title">Title</label>
<input type="text" name="foo[title]" id="foo-title">

Attributes that are already namespaced will get double-namespaced. For example, the following HTML:

html
<label for="bar-title">Title</label>
<input type="text" name="bar[title]" id="bar-title">

would become:

html
<label for="foo-bar-title">Title</label>
<input type="text" name="foo[bar][title]" id="foo-bar-title">

When a callable is passed to $html (supported as of Craft 3.7), the namespace will be set via setNamespace() before the callable is executed, in time for any JavaScript code that needs to be registered by the callable.

php
$settingsHtml = Craft::$app->view->namespaceInputs(function() use ($widget) {
    return $widget->getSettingsHtml();
}, 'widget-settings');

View source

Arguments

  • $html (callable, string) – The HTML code, or a callable that returns the HTML code
  • $namespace (string, null) – The namespace. Defaults to the active namespace.
  • $otherAttributes (boolean) – Whether id, for, and other attributes should be namespaced (in addition to name)
  • $withClasses (boolean) – Whether class names should be namespaced as well (affects both class attributes and class name CSS selectors within <style> tags). This will only have an effect if $otherAttributes is true.

Returns

string – The HTML with namespaced attributes

normalizeObjectTemplate()

Normalizes an object template for renderObjectTemplate().

View source

Arguments

Returns

string

registerAssetBundle()

Registers the named asset bundle.

All dependent asset bundles will be registered.

View source

Arguments

  • $name (string) – The class name of the asset bundle (without the leading backslash)
  • $position (integer, null) – If 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

yii\web\AssetBundle – The registered asset bundle instance

Throws

registerDeltaName()

Since
3.4.0

Registers a delta input name.

This can be either the name of a single form input, or a prefix used by multiple input names.

The input name will be namespaced with the currently active namespace, if any.

When a form that supports delta updates is submitted, any delta inputs (or groups of inputs) that didn’t change over the lifespan of the page will be omitted from the POST request.

Note that delta input names will only be registered if delta registration is active (see getIsDeltaRegistrationActive()).

View source

Arguments

  • $inputName (string)
  • $forceModified (boolean) – Whether the name should be considered modified regardless of the initial form value

registerHtml()

Since
3.5.0

Registers arbitrary HTML to be injected into the final page response.

View source

Arguments

  • $html (string) – The HTML code to be registered
  • $position (integer) – The position at which the HTML code should be inserted in the page. 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
  • $key (string, null) – The key that identifies the HTML code. If null, it will use a hash of the HTML as the key. If two HTML code blocks are registered with the same position and key, the latter will overwrite the former.

registerJs()

Registers a JS code block.

View source

Arguments

  • $js (string) – The JS code block to be registered

  • $position (integer) – The 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 jQuery(window).load(). Note that by using this position, the method will automatically register the jQuery js file.

  • POS_READY: enclosed within jQuery(document).ready(). This is the default value. Note that by using this position, the method will automatically register the jQuery js file.

  • $key (string, null) – The 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.

registerJsFile()

Registers a JS file.

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

View source

Arguments

  • $url (string) – The JS file to be registered.

  • $options (array) – The 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_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 craft\helpers\Html::jsFile() for other supported options.

  • $key (string, null) – The 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.

Throws

registerJsWithVars()

Since
3.7.31

Registers JavaScript code with the given variables, pre-JSON-encoded.

View source

Arguments

  • $jsFn (callable) – Callback function that returns the JS code to be registered.

  • $vars (array) – Array of variables that will be JSON-encoded before being passed to $jsFn.

  • $position (integer) – The 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 jQuery(window).load(). Note that by using this position, the method will automatically register the jQuery js file.

  • POS_READY: enclosed within jQuery(document).ready(). This is the default value. Note that by using this position, the method will automatically register the jQuery js file.

  • $key (string, null) – The 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.

registerScript()

Registers a generic <script> code block.

View source

Arguments

  • $script (string) – The generic <script> code block to be registered
  • $position (integer) – The position at which the generic <script> code block 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
  • $options (array) – The HTML attributes for the <script> tag.
  • $key (string, null) – The key that identifies the generic <script> code block. If null, it will use $script as the key. If two generic <script> code blocks are registered with the same key, the latter will overwrite the former.

registerTranslations()

Translates messages for a given translation category, so they will be available for Craft.t() calls in the control panel.

Note this should always be called before any JavaScript is registered that will need to use the translations, unless the JavaScript is registered at yii\web\View::POS_READY.

View source

Arguments

  • $category (string) – The category the messages are in
  • $messages (string[]) – The messages to be translated

registerTwigExtension()

Registers a new Twig extension, which will be added on existing environments and queued up for future environments.

View source

Arguments

  • $extension (\Twig\Extension\ExtensionInterface)

renderObjectTemplate()

Renders an object template.

The passed-in $object will be available to the template as an object variable.

The template will be parsed for “property tags” (e.g. {foo}), which will get replaced with full Twig output tags (e.g. {{ object.foo|raw }}.

If $object is an instance of yii\base\Arrayable, any attributes returned by its fields() or extraFields() methods will also be available as variables to the template.

View source

Arguments

  • $template (string) – The source template string
  • $object (mixed) – The object that should be passed into the template
  • $variables (array) – Any additional variables that should be available to the template
  • $templateMode (string) – The template mode to use.

Returns

string – The rendered template.

Throws

renderPageTemplate()

Renders a Twig template that represents an entire web page.

View source

Arguments

  • $template (string) – The name of the template to load
  • $variables (array) – The variables that should be available to the template
  • $templateMode (string, null) – The template mode to use

Returns

string – The rendering result

Throws

  • \Twig\Error\LoaderError
  • \Twig\Error\RuntimeError
  • \Twig\Error\SyntaxError
  • yii\base\Exception
    if $templateMode is invalid

renderString()

Renders a template defined in a string.

View source

Arguments

  • $template (string) – The source template string.
  • $variables (array) – Any variables that should be available to the template.
  • $templateMode (string) – The template mode to use.
  • $escapeHtml (boolean) – Whether dynamic HTML should be escaped

Returns

string – The rendered template.

Throws

  • \Twig\Error\LoaderError
  • \Twig\Error\SyntaxError

renderTemplate()

Renders a Twig template.

View source

Arguments

  • $template (string) – The name of the template to load
  • $variables (array) – The variables that should be available to the template
  • $templateMode (string, null) – The template mode to use

Returns

string – The rendering result

Throws

  • \Twig\Error\LoaderError
  • \Twig\Error\RuntimeError
  • \Twig\Error\SyntaxError
  • yii\base\Exception
    if $templateMode is invalid

resolveTemplate()

Finds a template on the file system and returns its path.

All of the following files will be searched for, in this order:

  • TemplateName
  • TemplateName.html
  • TemplateName.twig
  • TemplateName/index.html
  • TemplateName/index.twig

If this is a front-end request, the actual list of file extensions and index filenames are configurable via the config4:defaultTemplateExtensions and config4:indexTemplateFilenames config settings.

For example if you set the following in config/general.php:

php
'defaultTemplateExtensions' => ['htm'],
'indexTemplateFilenames' => ['default'],

then the following files would be searched for instead:

  • TemplateName
  • TemplateName.htm
  • TemplateName/default.htm

The actual directory that those files will depend on the current template mode (probably templates/ if it’s a front-end site request, and vendor/craftcms/cms/src/templates/ if it’s a Control Panel request).

If this is a front-end site request, a folder named after the current site handle will be checked first.

  • templates/SiteHandle/...
  • templates/...

And finally, if this is a control panel request and the template name includes multiple segments and the first segment of the template name matches a plugin’s handle, then Craft will look for a template named with the remaining segments within that plugin’s templates/ subfolder.

To put it all together, here’s where Craft would look for a template named “foo/bar”, depending on the type of request it is:

  • Front-end site requests:
    • templates/SiteHandle/foo/bar
    • templates/SiteHandle/foo/bar.html
    • templates/SiteHandle/foo/bar.twig
    • templates/SiteHandle/foo/bar/index.html
    • templates/SiteHandle/foo/bar/index.twig
    • templates/foo/bar
    • templates/foo/bar.html
    • templates/foo/bar.twig
    • templates/foo/bar/index.html
    • templates/foo/bar/index.twig
  • Control panel requests:
    • vendor/craftcms/cms/src/templates/foo/bar
    • vendor/craftcms/cms/src/templates/foo/bar.html
    • vendor/craftcms/cms/src/templates/foo/bar.twig
    • vendor/craftcms/cms/src/templates/foo/bar/index.html
    • vendor/craftcms/cms/src/templates/foo/bar/index.twig
    • path/to/fooplugin/templates/bar
    • path/to/fooplugin/templates/bar.html
    • path/to/fooplugin/templates/bar.twig
    • path/to/fooplugin/templates/bar/index.html
    • path/to/fooplugin/templates/bar/index.twig

View source

Arguments

  • $name (string) – The name of the template.
  • $templateMode (string, null) – The template mode to use.
  • $publicOnly (boolean) – Whether to only look for public templates (template paths that don’t start with the private template trigger).

Returns

string, false – The path to the template if it exists, or false.

Throws

  • \Twig\Error\LoaderError

setInitialDeltaValue()

Since
3.4.6

Sets the initial value of a delta input name.

See also getInitialDeltaValues()View source

Arguments

  • $inputName (string)
  • $value (mixed)

setIsDeltaRegistrationActive()

Since
3.4.0

Sets whether delta input name registration is active.

See also registerDeltaName()View source

Arguments

setNamespace()

Sets the active namespace.

This is the default namespaces that will be used when namespaceInputs(), namespaceInputName(), and namespaceInputId() are called, if their|null $namespace arguments are null.

View source

Arguments

  • $namespace (string, null) – The new namespace. Set to null to remove the namespace.

setRegisteredAssetBundles()

Since
3.0.10

Sets the asset bundle names that should be marked as already registered.

View source

Arguments

  • $names (string[]) – Asset bundle names

setRegisteredJsFiles()

Since
3.0.10

Sets the JS files that should be marked as already registered.

View source

Arguments

setTemplateMode()

Sets the current template mode.

The template mode defines:

  • the base path that templates should be looked for in
  • the default template file extensions that should be automatically added when looking for templates
  • the "index" template filenames that should be checked when looking for templates

View source

Arguments

  • $templateMode (string) – Either 'site' or 'cp'

Throws

setTemplatesPath()

Sets the base path that templates should be found in.

View source

Arguments

startAssetBundleBuffer()

Since
4.11.0

Starts a buffer for any asset bundles registered with registerAssetBundle().

The buffer’s contents can be cleared and returned later via clearAssetBundleBuffer().

See also clearAssetBundleBuffer()View source

startCssBuffer()

Since
3.7.0

Starts a buffer for any <style> tags registered with registerCss().

The buffer’s contents can be cleared and returned later via clearCssBuffer().

See also clearCssBuffer()View source

startCssFileBuffer()

Since
4.0.0

Starts a buffer for any <link> tags registered with registerCssFile().

The buffer’s contents can be cleared and returned later via clearCssFileBuffer().

See also clearCssFileBuffer()View source

startHtmlBuffer()

Since
4.3.0

Starts a buffer for any html tags registered with registerHtml().

View source

startJsBuffer()

Starts a buffer for any JavaScript code registered with registerJs().

The buffer’s contents can be cleared and returned later via clearJsBuffer().

See also clearJsBuffer()View source

startJsFileBuffer()

Since
4.0.0

Starts a buffer for any <script> tags registered with registerJsFile().

The buffer’s contents can be cleared and returned later via clearJsFileBuffer().

See also clearJsFileBuffer()View source

startMetaTagBuffer()

Since
4.5.8

Starts a buffer for any <meta> tags registered with registerMetaTag().

The buffer’s contents can be cleared and returned later via clearMetaTagBuffer().

See also clearMetaTagBuffer()View source

startScriptBuffer()

Since
3.7.0

Starts a buffer for any <script> tags registered with registerScript().

The buffer’s contents can be cleared and returned later via clearScriptBuffer().

See also clearScriptBuffer()View source

Protected Methods

MethodDescription
findViewFile()Finds the view file based on the given view name.
getRequestedViewFile()
registerAllAssetFiles()Registers all files provided by all registered asset bundles, including depending bundles files.
registerAssetFiles()Registers all files provided by an asset bundle including depending bundles files.
registerAssetFlashes()Registers any asset bundles and JS code that were queued-up in the session flash data.
renderBodyBeginHtml()Renders the content to be inserted at the beginning of the body section.
renderBodyEndHtml()Renders the content to be inserted at the end of the body section.
renderHeadHtml()Renders the content to be inserted in the head section.

registerAllAssetFiles()

Registers all files provided by all registered asset bundles, including depending bundles files.

Removes a bundle from assetBundles once files are registered.

View source

registerAssetFiles()

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

Removes a bundle from assetBundles once files are registered.

View source

Arguments

  • $name (string) – Name of the bundle to register

registerAssetFlashes()

Registers any asset bundles and JS code that were queued-up in the session flash data.

View source

Throws

renderBodyBeginHtml()

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.

View source

Returns

string – The rendered content

renderBodyEndHtml()

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.

View source

Arguments

  • $ajaxMode (boolean) – Whether 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

renderHeadHtml()

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.

View source

Returns

string – The rendered content

Constants

ConstantDescription
PH_BODY_BEGINThis is internally used as the placeholder for receiving the content registered for the beginning of the body section.
PH_BODY_ENDThis is internally used as the placeholder for receiving the content registered for the end of the body section.
PH_HEADThis is internally used as the placeholder for receiving the content registered for the head section.
POS_BEGINThe location of registered JavaScript code block or files.
POS_ENDThe location of registered JavaScript code block or files.
POS_HEADThe location of registered JavaScript code block or files.
POS_LOADThe location of registered JavaScript code block.
POS_READYThe location of registered JavaScript code block.
TEMPLATE_MODE_CP
TEMPLATE_MODE_SITE

Events

EVENT_AFTER_CREATE_TWIG

Type
craft\events\CreateTwigEvent
Since
4.3.0

The event that is triggered when a Twig environment is created.

See also createTwig()


EVENT_AFTER_REGISTER_ASSET_BUNDLE

Type
craft\events\AssetBundleEvent
Since
4.5.0

The event that is triggered after an asset bundle is registered


EVENT_AFTER_RENDER_PAGE_TEMPLATE

Type
craft\events\TemplateEvent

The event that is triggered after a page template gets rendered


EVENT_AFTER_RENDER_TEMPLATE

Type
craft\events\TemplateEvent

The event that is triggered after a template gets rendered


EVENT_BEFORE_RENDER_PAGE_TEMPLATE

Type
craft\events\TemplateEvent

The event that is triggered before a page template gets rendered


EVENT_BEFORE_RENDER_TEMPLATE

Type
craft\events\TemplateEvent

The event that is triggered before a template gets rendered


EVENT_REGISTER_CP_TEMPLATE_ROOTS

Type
craft\events\RegisterTemplateRootsEvent

The event that is triggered when registering control panel template roots


EVENT_REGISTER_SITE_TEMPLATE_ROOTS

Type
craft\events\RegisterTemplateRootsEvent

The event that is triggered when registering site template roots