TemplatesService
- Type
- Class
- Namespace
- Craft
- Inherits
- Craft\TemplatesService » Craft\BaseApplicationComponent » CApplicationComponent (opens new window) » CComponent (opens new window)
- Implements
IApplicationComponent
- Since
- 1.0
TemplatesService provides APIs for rendering templates, as well as interacting with other areas of Craft’s templating system.
An instance of TemplatesService is globally accessible in Craft via {@link WebApp::templates craft()->templates
}.
See also http://craftcms.com
View source (opens new window)
# Public Properties
Property | Description |
---|---|
$behaviors (opens new window) | array (opens new window) – The behaviors that should be attached to this component. |
# Public Methods
Method | Description |
---|---|
__call() (opens new window) | Calls the named method which is not a class method. |
__get() (opens new window) | Returns a property value, an event handler list or a behavior based on its name. |
__isset() (opens new window) | Checks if a property value is null. |
__set() (opens new window) | Sets value of a component property. |
__unset() (opens new window) | Sets a component property to be null. |
asa() (opens new window) | Returns the named behavior object. |
attachBehavior() (opens new window) | Attaches a behavior to this component. |
attachBehaviors() (opens new window) | Attaches a list of behaviors to the component. |
attachEventHandler() (opens new window) | Attaches an event handler to an event. |
canGetProperty() (opens new window) | Determines whether a property can be read. |
canSetProperty() (opens new window) | Determines whether a property can be set. |
clearJsBuffer() | Clears and ends a Javascript buffer, returning whatever Javascript code was included while the buffer was active. |
detachBehavior() (opens new window) | Detaches a behavior from the component. |
detachBehaviors() (opens new window) | Detaches all behaviors from the component. |
detachEventHandler() (opens new window) | Detaches an existing event handler. |
disableBehavior() (opens new window) | Disables an attached behavior. |
disableBehaviors() (opens new window) | Disables all behaviors attached to this component. |
doesTemplateExist() | Returns whether a template exists. |
enableBehavior() (opens new window) | Enables an attached behavior. |
enableBehaviors() (opens new window) | Enables all behaviors attached to this component. |
evaluateExpression() (opens new window) | Evaluates a PHP expression or callback under the context of this component. |
findTemplate() | Finds a template on the file system and returns its path. |
formatInputId() | Formats an ID out of an input name. |
getCsrfInput() | Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation (opens new window) is set to true. |
getEventHandlers() (opens new window) | Returns the list of attached event handlers for an event. |
getFootHtml() | Returns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue. |
getHeadHtml() | Returns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue. |
getIsInitialized() (opens new window) | Checks if this application component has been initialized. |
getNamespace() | Returns the active namespace. |
getRenderingTemplate() | Returns the template path that is currently being rendered, or the full template if {@link renderString()} or {@link renderObjectTemplate()} was called. |
getScriptTag() | Wraps some Javascript code in a <script> tag. |
getTemplateMode() | Returns the current template mode (either 'site' or 'cp'). |
getTemplatesPath() | Returns the base path that templates should be found in. |
getTranslations() | Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue. |
getTwig() | Returns the Twig Environment instance for a given template loader class. |
hasEvent() (opens new window) | Determines whether an event is defined. |
hasEventHandler() (opens new window) | Checks whether the named event has attached handlers. |
hasProperty() (opens new window) | Determines whether a property is defined. |
hook() | Queues up a method to be called by a given template hook. |
includeCss() | Prepares CSS for inclusion in the template. |
includeCssFile() | Prepares a CSS file for inclusion in the template. |
includeCssResource() | Prepares a CSS file from resources/ for inclusion in the template. |
includeFootHtml() | Prepares an HTML node for inclusion right above the </body> in the template. |
includeFootNode() | Prepares an HTML node for inclusion right above the in the template. |
includeHeadHtml() | Prepares some HTML for inclusion in the <head> of the template. |
includeHeadNode() | Prepares some HTML for inclusion in the <head> of the template. |
includeHiResCss() | Prepares hi-res screen-targeting CSS for inclusion in the template. |
includeJs() | Prepares JS for inclusion in the template. |
includeJsFile() | Prepares a JS file for inclusion in the template. |
includeJsResource() | Prepares a JS file from resources/ for inclusion in the template. |
includeTranslations() | Prepares translations for inclusion in the template, to be used by the JS. |
init() | Initializes the application component. |
invokeHook() | Invokes a template hook. |
isInitialized() | Checks if this application component has been initialized yet, or not. |
isRendering() | Returns whether a template is currently being rendered. |
namespaceInputId() | Namespaces an input ID. |
namespaceInputName() | Namespaces an input name. |
namespaceInputs() | Renames HTML input names so they belong to a namespace. |
onPluginsLoaded() | Loads plugin-supplied Twig extensions now that all plugins have been loaded. |
raiseEvent() (opens new window) | Raises an event. |
render() | Renders a template. |
renderMacro() | Renders a macro within a given template. |
renderObjectTemplate() | Renders a micro template for accessing properties of a single object. |
renderString() | Renders a template defined in a string. |
setNamespace() | Sets the active namespace. |
setTemplateMode() | Sets the current template mode. |
setTemplatesPath() | Sets the base path that templates should be found in. |
startJsBuffer() | Starts a Javascript buffer. |
# clearJsBuffer()
Clears and ends a Javascript buffer, returning whatever Javascript code was included while the buffer was active.
View source (opens new window)
Arguments
$scriptTag
(boolean (opens new window)) – Whether the Javascript code should be wrapped in a<script>
tag. Defaults totrue
.
Returns
string (opens new window), null (opens new window), false (opens new window) – Returns false
if there isn’t an active Javascript buffer, null
if there is an
active buffer but no Javascript code was actually added to it, or a string of the
included Javascript code if there was any.
Signature
public string, null, false clearJsBuffer ( $scriptTag = true )
# doesTemplateExist()
Returns whether a template exists. Internally, this will just call {@link findTemplate()} with the given template name, and return whether that method found anything.
View source (opens new window)
Arguments
$name
(string (opens new window)) – The name of the template.
Returns
boolean (opens new window) – Whether the template exists.
Signature
public boolean doesTemplateExist ( $name )
# findTemplate()
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 defaultTemplateExtensions (opens new window) and indexTemplateFilenames (opens new window) config settings.
For example if you set the following in config/general.php:
'defaultTemplateExtensions' => array('htm'),
'indexTemplateFilenames' => array('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 {@link setTemplateMode() template mode} (probably craft/templates/ if it’s a front-end site request, and craft/app/templates/ if it’s a Control Panel request).
If this is a front-end site request, a folder named after the current locale ID will be checked first.
- craft/templates/LocaleID/...
- craft/templates/...
And finaly, 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:
- craft/templates/LocaleID/foo/bar
- craft/templates/LocaleID/foo/bar.html
- craft/templates/LocaleID/foo/bar.twig
- craft/templates/LocaleID/foo/bar/index.html
- craft/templates/LocaleID/foo/bar/index.twig
- craft/templates/foo/bar
- craft/templates/foo/bar.html
- craft/templates/foo/bar.twig
- craft/templates/foo/bar/index.html
- craft/templates/foo/bar/index.twig
Control Panel requests:
- craft/app/templates/foo/bar
- craft/app/templates/foo/bar.html
- craft/app/templates/foo/bar.twig
- craft/app/templates/foo/bar/index.html
- craft/app/templates/foo/bar/index.twig
- craft/plugins/foo/templates/bar
- craft/plugins/foo/templates/bar.html
- craft/plugins/foo/templates/bar.twig
- craft/plugins/foo/templates/bar/index.html
- craft/plugins/foo/templates/bar/index.twig
View source (opens new window)
Arguments
$name
(string (opens new window)) – The name of the template.
Returns
string (opens new window), false (opens new window) – The path to the template if it exists, or false
.
Signature
public string, false findTemplate ( $name )
# formatInputId()
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 (opens new window)
Arguments
$inputName
(string (opens new window)) – The input name.
Returns
string (opens new window) – The input ID.
Signature
public string formatInputId ( $inputName )
# getCsrfInput()
Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation (opens new window) is set to true.
View source (opens new window)
Returns
string (opens new window) – If 'enabledCsrfProtection' is enabled, the HTML for the hidden input, otherwise an empty string.
Signature
public string getCsrfInput ( )
# getFootHtml()
Returns the HTML prepared for inclusion right above the </body>
in the template, and flushes out the foot HTML
queue.
This will include:
- Any Javascript files included in the previous request using {@link UserSessionService::addJsResourceFlash()}
- Any Javascript included in the previous request using {@link UserSessionService::addJsFlash()}
- Any Javascript files included using {@link includeJsFile()} or {@link includeJsResource()}
- Any Javascript code included using {@link includeJs()}
- Any HTML included using {@link includeFootHtml()}
View source (opens new window)
Returns
Signature
public string getFootHtml ( )
# getHeadHtml()
Returns the HTML prepared for inclusion in the <head>
of the template, and flushes out the head HTML queue.
This will include:
- Any CSS files included using {@link includeCssFile()} or {@link includeCssResource()}
- Any CSS included using {@link includeCss()} or {@link includeHiResCss()}
- Any HTML included using {@link includeHeadHtml()}
View source (opens new window)
Returns
Signature
public string getHeadHtml ( )
# getNamespace()
Returns the active namespace. This is the default namespaces that will be used when {@link namespaceInputs()}, {@link namespaceInputName()}, and {@link namespaceInputId()} are called, if their $namespace arguments are null.
View source (opens new window)
Returns
string (opens new window) – The namespace.
Signature
public string getNamespace ( )
# getRenderingTemplate()
Returns the template path that is currently being rendered, or the full template if {@link renderString()} or {@link renderObjectTemplate()} was called.
View source (opens new window)
Returns
mixed
– The template that is being rendered.
Signature
public mixed getRenderingTemplate ( )
# getScriptTag()
Wraps some Javascript code in a <script>
tag.
View source (opens new window)
Arguments
$js
(string (opens new window), array (opens new window)) – The Javascript code.
Returns
string (opens new window) – The <script>
tag.
Signature
public string getScriptTag ( $js )
# getTemplateMode()
Returns the current template mode (either 'site' or 'cp').
View source (opens new window)
Returns
string (opens new window) – Either 'site' or 'cp'.
Signature
public string getTemplateMode ( )
# getTemplatesPath()
Signature
public string getTemplatesPath ( )
# getTranslations()
Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue.
View source (opens new window)
Returns
string (opens new window) – A JSON-encoded array of source/translation message mappings.
Signature
public string getTranslations ( )
# getTwig()
Returns the Twig Environment instance for a given template loader class.
View source (opens new window)
Arguments
$loaderClass
(string (opens new window)) – The name of the class that should be initialized as the Twig instance’s template loader. If no class is passed in, {@link TemplateLoader} will be used.$options
Returns
Craft\TwigEnvironment – The Twig Environment instance.
Signature
public Craft\TwigEnvironment getTwig ( $loaderClass = null, $options = [] )
# hook()
Queues up a method to be called by a given template hook. For example, if you place this in your plugin’s {@link BasePlugin::init() init()} method:
craft()->templates->hook('myAwesomeHook', function(&$context)
{
$context['foo'] = 'bar';
return 'Hey!';
});
you would then be able to add this to any template:
{% 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.
View source (opens new window)
Arguments
$hook
(string (opens new window)) – The hook name.$method
(callback
) – The callback function.
Returns
Signature
public null hook ( $hook, $method )
# includeCss()
Prepares CSS for inclusion in the template.
View source (opens new window)
Arguments
$css
(string (opens new window)) – The CSS.$first
(boolean (opens new window)) – Whether the CSS should be included before any other CSS that was already included with this method.
Returns
Signature
public null includeCss ( $css, $first = false )
# includeCssFile()
Prepares a CSS file for inclusion in the template.
View source (opens new window)
Arguments
$url
(string (opens new window)) – The URL to the CSS file.$first
(boolean (opens new window)) – Whether the CSS file should be included before any other CSS files that were already included with this method.
Returns
Signature
public null includeCssFile ( $url, $first = false )
# includeCssResource()
Prepares a CSS file from resources/ for inclusion in the template.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The resource path to the CSS file.$first
(boolean (opens new window)) – Whether the CSS file should be included before any other CSS files that were already included with this method.
Returns
Signature
public null includeCssResource ( $path, $first = false )
# includeFootHtml()
Prepares an HTML node for inclusion right above the </body>
in the template.
View source (opens new window)
Arguments
$node
(string (opens new window)) – The HTML to be included in the template.$first
(boolean (opens new window)) – Whether the HTML should be included before any other HTML that was already included with this method.
Returns
Signature
public null includeFootHtml ( $node, $first = false )
# includeFootNode()
Prepares an HTML node for inclusion right above the in the template.
View source (opens new window)
Arguments
$node
(string (opens new window)) – The HTML to be included in the template.$first
(boolean (opens new window)) – Whether the HTML should be included before any other HTML that was already included with this method.
Signature
public void includeFootNode ( $node, $first = false )
# includeHeadHtml()
Prepares some HTML for inclusion in the <head>
of the template.
View source (opens new window)
Arguments
$node
(string (opens new window)) – The HTML to be included in the template.$first
(boolean (opens new window)) – Whether the HTML should be included before any other HTML that was already included with this method.
Returns
Signature
public null includeHeadHtml ( $node, $first = false )
# includeHeadNode()
DEPRECATED
Deprecated Deprecated in 1.1. Use {@link includeHeadHtml()} instead.
Prepares some HTML for inclusion in the <head>
of the template.
View source (opens new window)
Arguments
$node
(string (opens new window)) – The HTML to be included in the template.$first
(boolean (opens new window)) – Whether the HTML should be included before any other HTML that was already included with this method.
Returns
Signature
public null includeHeadNode ( $node, $first = false )
# includeHiResCss()
Prepares hi-res screen-targeting CSS for inclusion in the template.
View source (opens new window)
Arguments
$css
(string (opens new window)) – The CSS.$first
(boolean (opens new window)) – Whether the CSS should be included before any other CSS that was already included with this method.
Returns
Signature
public null includeHiResCss ( $css, $first = false )
# includeJs()
Prepares JS for inclusion in the template.
View source (opens new window)
Arguments
$js
(string (opens new window)) – The Javascript code.$first
(boolean (opens new window)) – Whether the Javascript code should be included before any other Javascript code that was already included with this method.
Returns
Signature
public null includeJs ( $js, $first = false )
# includeJsFile()
Prepares a JS file for inclusion in the template.
View source (opens new window)
Arguments
$url
(string (opens new window)) – The URL to the JS file.$first
(boolean (opens new window)) – Whether the JS file should be included before any other JS files that were already included with this method.
Returns
Signature
public null includeJsFile ( $url, $first = false )
# includeJsResource()
Prepares a JS file from resources/ for inclusion in the template.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The resource path to the JS file.$first
(boolean (opens new window)) – Whether the JS file should be included before any other JS files that were already included with this method.
Returns
Signature
public null includeJsResource ( $path, $first = false )
# includeTranslations()
Prepares translations for inclusion in the template, to be used by the JS.
View source (opens new window)
Returns
Signature
public null includeTranslations ( )
# init()
Signature
public null init ( )
# invokeHook()
Invokes a template hook.
This is called by {@link Hook_Node {% hook %}
tags).
View source (opens new window)
Arguments
$hook
(string (opens new window)) – The hook name.$context
Returns
string (opens new window) – Whatever the hooks returned.
Signature
public string invokeHook ( $hook, &$context )
# isRendering()
Returns whether a template is currently being rendered.
View source (opens new window)
Returns
boolean (opens new window) – Whether a template is currently being rendered.
Signature
public boolean isRendering ( )
# namespaceInputId()
Namespaces an input ID.
This method applies the same namespacing treatment that {@link namespaceInputs()} does to id=
attributes,
but only to a single value, which is passed directly into this method.
View source (opens new window)
Arguments
$inputId
(string (opens new window)) – The input ID that should be namespaced.$namespace
(string (opens new window)) – The namespace. Defaults to the {@link getNamespace() active namespace}.
Returns
string (opens new window) – The namespaced input ID.
Signature
public string namespaceInputId ( $inputId, $namespace = null )
# namespaceInputName()
Namespaces an input name.
This method applies the same namespacing treatment that {@link namespaceInputs()} does to name=
attributes,
but only to a single value, which is passed directly into this method.
View source (opens new window)
Arguments
$inputName
(string (opens new window)) – The input name that should be namespaced.$namespace
(string (opens new window)) – The namespace. Defaults to the {@link getNamespace() active namespace}.
Returns
string (opens new window) – The namespaced input name.
Signature
public string namespaceInputName ( $inputName, $namespace = null )
# 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 {@link getNamespace() 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:
<label for="title">Title</label>
<input type="text" name="title" id="title">
would become this, if it were namespaced with “foo”:
<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:
<label for="bar-title">Title</label>
<input type="text" name="bar[title]" id="title">
would become:
<label for="foo-bar-title">Title</label>
<input type="text" name="foo[bar][title]" id="foo-bar-title">
View source (opens new window)
Arguments
$html
(string (opens new window)) – The template with the inputs.$namespace
(string (opens new window)) – The namespace. Defaults to the {@link getNamespace() active namespace}.$otherAttributes
(boolean (opens new window)) – Whether id=, for=, etc., should also be namespaced. Defaults totrue
.
Returns
string (opens new window) – The HTML with namespaced input names.
Signature
public string namespaceInputs ( $html, $namespace = null, $otherAttributes = true )
# onPluginsLoaded()
Loads plugin-supplied Twig extensions now that all plugins have been loaded.
View source (opens new window)
Arguments
$event
(Craft\Event)
Returns
Signature
public null onPluginsLoaded ( Craft\Event $event )
# render()
Renders a template.
View source (opens new window)
Arguments
$template
(mixed
) – The name of the template to load, or a StringTemplate object.$variables
(array (opens new window)) – The variables that should be available to the template.$safeMode
(boolean (opens new window)) – Whether to limit what's available to in the Twig context in the interest of security.
Returns
string (opens new window) – The rendered template.
Signature
public string render ( $template, $variables = [], $safeMode = false )
# renderMacro()
Renders a macro within a given template.
View source (opens new window)
Arguments
$template
(string (opens new window)) – The name of the template the macro lives in.$macro
(string (opens new window)) – The name of the macro.$args
(array (opens new window)) – Any arguments that should be passed to the macro.
Returns
string (opens new window) – The rendered macro output.
Signature
public string renderMacro ( $template, $macro, $args = [] )
# renderObjectTemplate()
Renders a micro template for accessing properties of a single object.
The template will be parsed for {variables} that are delimited by single braces, which will get replaced with
full Twig output tags, i.e. {{ object.variable }}
. Regular Twig tags are also supported.
View source (opens new window)
Arguments
$template
(string (opens new window)) – The source template string.$object
(mixed
) – The object that should be passed into the template.$safeMode
(boolean (opens new window)) – Whether to limit what's available to in the Twig context in the interest of security.
Returns
string (opens new window) – The rendered template.
Signature
public string renderObjectTemplate ( $template, $object, $safeMode = false )
# renderString()
Renders a template defined in a string.
View source (opens new window)
Arguments
$template
(string (opens new window)) – The source template string.$variables
(array (opens new window)) – Any variables that should be available to the template.$safeMode
(boolean (opens new window)) – Whether to limit what's available to in the Twig context in the interest of security.
Returns
string (opens new window) – The rendered template.
Signature
public string renderString ( $template, $variables = [], $safeMode = false )
# setNamespace()
Sets the active namespace. This is the default namespaces that will be used when {@link namespaceInputs()}, {@link namespaceInputName()}, and {@link namespaceInputId()} are called, if their $namespace arguments are null.
View source (opens new window)
Arguments
$namespace
(string (opens new window)) – The new namespace.
Returns
Signature
public null setNamespace ( $namespace )
# 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 sholud be checked when looking for templates
View source (opens new window)
Arguments
$templateMode
(string (opens new window)) – Either 'site' or 'cp'
Returns
void
Throws
- Craft\Exception
if $templateMode is invalid
Signature
public void setTemplateMode ( $templateMode )
# setTemplatesPath()
Sets the base path that templates should be found in.
View source (opens new window)
Arguments
$templatesPath
(string (opens new window))
Returns
void
Signature
public void setTemplatesPath ( $templatesPath )
# startJsBuffer()
Starts a Javascript buffer. Javascript buffers work similarly to output buffers (opens new window) in PHP. Once you’ve started a Javascript buffer, any Javascript code included with {@link includeJs()} will be included in a buffer, and you will have the opportunity to fetch all of that code via {@link clearJsBuffer()} without having it actually get output to the page.
View source (opens new window)
Returns
Signature
public null startJsBuffer ( )