Craft 2 Class Reference

Class TemplatesService

Package
craft.app.services
Namespace
Craft
Inheritance
class TemplatesService » BaseApplicationComponent » \CApplicationComponent » \CComponent
Implements
\IApplicationComponent
Since
1.0
Source Code
craft/app/services/TemplatesService.php

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 craft()->templates.

Public Properties
Property Type Description Defined By
behaviors array the behaviors that should be attached to this component. \CApplicationComponent
csrfInput string Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation is set to true. TemplatesService
footHtml string Returns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue. TemplatesService
headHtml string Returns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue. TemplatesService
isInitialized bool Checks if this application component has been initialized. \CApplicationComponent
namespace string Returns the active namespace. TemplatesService
renderingTemplate mixed Returns the template path that is currently being rendered, or the full template if renderString() or renderObjectTemplate() was called. TemplatesService
templateMode string Returns the current template mode (either 'site' or 'cp'). TemplatesService
templatesPath string Returns the base path that templates should be found in. TemplatesService
translations string Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue. TemplatesService
twig TwigEnvironment Returns the Twig Environment instance for a given template loader class. TemplatesService
Public Methods
Method Description Defined By
__call() Calls the named method which is not a class method. \CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. \CComponent
__isset() Checks if a property value is null. \CComponent
__set() Sets value of a component property. \CComponent
__unset() Sets a component property to be null. \CComponent
asa() Returns the named behavior object. \CComponent
attachBehavior() Attaches a behavior to this component. \CComponent
attachBehaviors() Attaches a list of behaviors to the component. \CComponent
attachEventHandler() Attaches an event handler to an event. \CComponent
canGetProperty() Determines whether a property can be read. \CComponent
canSetProperty() Determines whether a property can be set. \CComponent
clearJsBuffer() Clears and ends a Javascript buffer, returning whatever Javascript code was included while the buffer was active. TemplatesService
detachBehavior() Detaches a behavior from the component. \CComponent
detachBehaviors() Detaches all behaviors from the component. \CComponent
detachEventHandler() Detaches an existing event handler. \CComponent
disableBehavior() Disables an attached behavior. \CComponent
disableBehaviors() Disables all behaviors attached to this component. \CComponent
doesTemplateExist() Returns whether a template exists. TemplatesService
enableBehavior() Enables an attached behavior. \CComponent
enableBehaviors() Enables all behaviors attached to this component. \CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. \CComponent
findTemplate() Finds a template on the file system and returns its path. TemplatesService
formatInputId() Formats an ID out of an input name. TemplatesService
getCsrfInput() Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation is set to true. TemplatesService
getEventHandlers() Returns the list of attached event handlers for an event. \CComponent
getFootHtml() Returns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue. TemplatesService
getHeadHtml() Returns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue. TemplatesService
getIsInitialized() Checks if this application component has been initialized. \CApplicationComponent
getNamespace() Returns the active namespace. TemplatesService
getRenderingTemplate() Returns the template path that is currently being rendered, or the full template if renderString() or renderObjectTemplate() was called. TemplatesService
getScriptTag() Wraps some Javascript code in a <script> tag. TemplatesService
getTemplateMode() Returns the current template mode (either 'site' or 'cp'). TemplatesService
getTemplatesPath() Returns the base path that templates should be found in. TemplatesService
getTranslations() Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue. TemplatesService
getTwig() Returns the Twig Environment instance for a given template loader class. TemplatesService
hasEvent() Determines whether an event is defined. \CComponent
hasEventHandler() Checks whether the named event has attached handlers. \CComponent
hasProperty() Determines whether a property is defined. \CComponent
hook() Queues up a method to be called by a given template hook. TemplatesService
includeCss() Prepares CSS for inclusion in the template. TemplatesService
includeCssFile() Prepares a CSS file for inclusion in the template. TemplatesService
includeCssResource() Prepares a CSS file from resources/ for inclusion in the template. TemplatesService
includeFootHtml() Prepares an HTML node for inclusion right above the </body> in the template. TemplatesService
includeFootNode() Prepares an HTML node for inclusion right above the in the template. TemplatesService
includeHeadHtml() Prepares some HTML for inclusion in the <head> of the template. TemplatesService
includeHeadNode() Prepares some HTML for inclusion in the <head> of the template. TemplatesService
includeHiResCss() Prepares hi-res screen-targeting CSS for inclusion in the template. TemplatesService
includeJs() Prepares JS for inclusion in the template. TemplatesService
includeJsFile() Prepares a JS file for inclusion in the template. TemplatesService
includeJsResource() Prepares a JS file from resources/ for inclusion in the template. TemplatesService
includeTranslations() Prepares translations for inclusion in the template, to be used by the JS. TemplatesService
init() Initializes the application component. TemplatesService
invokeHook() Invokes a template hook. TemplatesService
isInitialized() Checks if this application component has been initialized yet, or not. BaseApplicationComponent
isRendering() Returns whether a template is currently being rendered. TemplatesService
namespaceInputId() Namespaces an input ID. TemplatesService
namespaceInputName() Namespaces an input name. TemplatesService
namespaceInputs() Renames HTML input names so they belong to a namespace. TemplatesService
onPluginsLoaded() Loads plugin-supplied Twig extensions now that all plugins have been loaded. TemplatesService
raiseEvent() Raises an event. \CComponent
render() Renders a template. TemplatesService
renderMacro() Renders a macro within a given template. TemplatesService
renderObjectTemplate() Renders a micro template for accessing properties of a single object. TemplatesService
renderString() Renders a template defined in a string. TemplatesService
setNamespace() Sets the active namespace. TemplatesService
setTemplateMode() Sets the current template mode. TemplatesService
setTemplatesPath() Sets the base path that templates should be found in. TemplatesService
startJsBuffer() Starts a Javascript buffer. TemplatesService
Events
Event Description Defined By
onPluginsLoaded Loads plugin-supplied Twig extensions now that all plugins have been loaded. TemplatesService

Property Details

csrfInput public property #

Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation is set to true.

public string getCsrfInput()

footHtml public property #

Returns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue.

This will include:

public string getFootHtml()

headHtml public property #

Returns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue.

This will include:

public string getHeadHtml()

namespace public property #

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.

public string getNamespace()
public null setNamespace(string $namespace)

renderingTemplate public property #

Returns the template path that is currently being rendered, or the full template if renderString() or renderObjectTemplate() was called.

public mixed getRenderingTemplate()

templateMode public property #

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

public string getTemplateMode()
public void setTemplateMode(string $templateMode)

templatesPath public property #

Returns the base path that templates should be found in.

public string getTemplatesPath()
public void setTemplatesPath(string $templatesPath)

translations public property #

Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue.

public string getTranslations()

twig public property #

Returns the Twig Environment instance for a given template loader class.

public TwigEnvironment getTwig(string $loaderClass = null, $options = array (
))

Method Details

clearJsBuffer() public method #

Clears and ends a Javascript buffer, returning whatever Javascript code was included while the buffer was active.

public string|null|false clearJsBuffer(bool $scriptTag = true)
$scriptTag bool Whether the Javascript code should be wrapped in a <script> tag. Defaults to true.
Returns string / null / false 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.

doesTemplateExist() public method #

Returns whether a template exists.

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

public bool doesTemplateExist(string $name)
$name string The name of the template.
Returns bool Whether the template exists.

findTemplate() public method #

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

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

If this is a front-end request, the actual list of file extensions and index filenames are configurable via the defaultTemplateExtensions and indexTemplateFilenames 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:

The actual directory that those files will depend on the current 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.

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:

public string|false findTemplate(string $name)
$name string The name of the template.
Returns string / false The path to the template if it exists, or false.

formatInputId() public method #

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
public string formatInputId(string $inputName)
$inputName string The input name.
Returns string The input ID.

getCsrfInput() public method #

Returns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation is set to true.

public string getCsrfInput()
Returns string If 'enabledCsrfProtection' is enabled, the HTML for the hidden input, otherwise an empty string.

getFootHtml() public method #

Returns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue.

This will include:

public string getFootHtml()
Returns string

getHeadHtml() public method #

Returns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue.

This will include:

public string getHeadHtml()
Returns string

getNamespace() public method #

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.

public string getNamespace()
Returns string The namespace.

getRenderingTemplate() public method #

Returns the template path that is currently being rendered, or the full template if renderString() or renderObjectTemplate() was called.

public mixed getRenderingTemplate()
Returns mixed The template that is being rendered.

getScriptTag() public method #

Wraps some Javascript code in a <script> tag.

public string getScriptTag(string|array $js)
$js string / array The Javascript code.
Returns string The <script> tag.

getTemplateMode() public method #

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

public string getTemplateMode()
Returns string Either 'site' or 'cp'.

getTemplatesPath() public method #

Returns the base path that templates should be found in.

public string getTemplatesPath()
Returns string

getTranslations() public method #

Returns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue.

public string getTranslations()
Returns string A JSON-encoded array of source/translation message mappings.

getTwig() public method #

Returns the Twig Environment instance for a given template loader class.

public TwigEnvironment getTwig(string $loaderClass = null, $options = array (
))
$loaderClass string The name of the class that should be initialized as the Twig instance’s template loader. If no class is passed in, TemplateLoader will be used.
$options
Returns TwigEnvironment The Twig Environment instance.

hook() public method #

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

For example, if you place this in your plugin’s 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.

public null hook(string $hook, callback $method)
$hook string The hook name.
$method callback The callback function.

includeCss() public method #

Prepares CSS for inclusion in the template.

public null includeCss(string $css, bool $first = false)
$css string The CSS.
$first bool Whether the CSS should be included before any other CSS that was already included with this method.

includeCssFile() public method #

Prepares a CSS file for inclusion in the template.

public null includeCssFile(string $url, bool $first = false)
$url string The URL to the CSS file.
$first bool Whether the CSS file should be included before any other CSS files that were already included with this method.

includeCssResource() public method #

Prepares a CSS file from resources/ for inclusion in the template.

public null includeCssResource(string $path, bool $first = false)
$path string The resource path to the CSS file.
$first bool Whether the CSS file should be included before any other CSS files that were already included with this method.

includeFootHtml() public method #

Prepares an HTML node for inclusion right above the </body> in the template.

public null includeFootHtml(string $node, bool $first = false)
$node string The HTML to be included in the template.
$first bool Whether the HTML should be included before any other HTML that was already included with this method.

includeFootNode() public method #

Prepares an HTML node for inclusion right above the in the template.

public void includeFootNode(string $node, bool $first = false)
$node string The HTML to be included in the template.
$first bool Whether the HTML should be included before any other HTML that was already included with this method.

includeHeadHtml() public method #

Prepares some HTML for inclusion in the <head> of the template.

public null includeHeadHtml(string $node, bool $first = false)
$node string The HTML to be included in the template.
$first bool Whether the HTML should be included before any other HTML that was already included with this method.

includeHeadNode() public method #

Prepares some HTML for inclusion in the <head> of the template.

Deprecated in 1.1. Use includeHeadHtml() instead.

public null includeHeadNode(string $node, bool $first = false)
$node string The HTML to be included in the template.
$first bool Whether the HTML should be included before any other HTML that was already included with this method.

includeHiResCss() public method #

Prepares hi-res screen-targeting CSS for inclusion in the template.

public null includeHiResCss(string $css, bool $first = false)
$css string The CSS.
$first bool Whether the CSS should be included before any other CSS that was already included with this method.

includeJs() public method #

Prepares JS for inclusion in the template.

public null includeJs(string $js, bool $first = false)
$js string The Javascript code.
$first bool Whether the Javascript code should be included before any other Javascript code that was already included with this method.

includeJsFile() public method #

Prepares a JS file for inclusion in the template.

public null includeJsFile(string $url, bool $first = false)
$url string The URL to the JS file.
$first bool Whether the JS file should be included before any other JS files that were already included with this method.

includeJsResource() public method #

Prepares a JS file from resources/ for inclusion in the template.

public null includeJsResource(string $path, bool $first = false)
$path string The resource path to the JS file.
$first bool Whether the JS file should be included before any other JS files that were already included with this method.

includeTranslations() public method #

Prepares translations for inclusion in the template, to be used by the JS.

public null includeTranslations()

init() public method #

Initializes the application component.

public null init()

invokeHook() public method #

Invokes a template hook.

This is called by {% hook % tags).

public string invokeHook(string $hook, array &$context)
$hook string The hook name.
&$context array The current template context.
Returns string Whatever the hooks returned.

isRendering() public method #

Returns whether a template is currently being rendered.

public bool isRendering()
Returns bool Whether a template is currently being rendered.

namespaceInputId() public method #

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.

public string namespaceInputId(string $inputId, string $namespace = null)
$inputId string The input ID that should be namespaced.
$namespace string The namespace. Defaults to the active namespace.
Returns string The namespaced input ID.

namespaceInputName() public method #

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.

public string namespaceInputName(string $inputName, string $namespace = null)
$inputName string The input name that should be namespaced.
$namespace string The namespace. Defaults to the active namespace.
Returns string The namespaced input name.

namespaceInputs() public method #

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:

<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">
public string namespaceInputs(string $html, string $namespace = null, bool $otherAttributes = true)
$html string The template with the inputs.
$namespace string The namespace. Defaults to the active namespace.
$otherAttributes bool Whether id=, for=, etc., should also be namespaced. Defaults to true.
Returns string The HTML with namespaced input names.

onPluginsLoaded() public method #

Loads plugin-supplied Twig extensions now that all plugins have been loaded.

public null onPluginsLoaded(Event $event)
$event Event

render() public method #

Renders a template.

public string render(mixed $template, array $variables = array (
), bool $safeMode = false)
$template mixed The name of the template to load, or a StringTemplate object.
$variables array The variables that should be available to the template.
$safeMode bool Whether to limit what's available to in the Twig context in the interest of security.
Returns string The rendered template.

renderMacro() public method #

Renders a macro within a given template.

public string renderMacro(string $template, string $macro, array $args = array (
))
$template string The name of the template the macro lives in.
$macro string The name of the macro.
$args array Any arguments that should be passed to the macro.
Returns string The rendered macro output.

renderObjectTemplate() public method #

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.

public string renderObjectTemplate(string $template, mixed $object, bool $safeMode = false)
$template string The source template string.
$object mixed The object that should be passed into the template.
$safeMode bool Whether to limit what's available to in the Twig context in the interest of security.
Returns string The rendered template.

renderString() public method #

Renders a template defined in a string.

public string renderString(string $template, array $variables = array (
), bool $safeMode = false)
$template string The source template string.
$variables array Any variables that should be available to the template.
$safeMode bool Whether to limit what's available to in the Twig context in the interest of security.
Returns string The rendered template.

setNamespace() public method #

Sets 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.

public null setNamespace(string $namespace)
$namespace string The new namespace.

setTemplateMode() public method #

Sets the current template mode.

The template mode defines:

public void setTemplateMode(string $templateMode)
$templateMode string Either 'site' or 'cp'
Returns void

setTemplatesPath() public method #

Sets the base path that templates should be found in.

public void setTemplatesPath(string $templatesPath)
$templatesPath string
Returns void

startJsBuffer() public method #

Starts a Javascript buffer.

Javascript buffers work similarly to output buffers in PHP. Once you’ve started a Javascript buffer, any Javascript code included with includeJs() will be included in a buffer, and you will have the opportunity to fetch all of that code via clearJsBuffer() without having it actually get output to the page.

public null startJsBuffer()