TemplatesService

Type
Class
Namespace
Craft
Inherits
Craft\TemplatesService » Craft\BaseApplicationComponent » CApplicationComponent » CComponent
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

Public Properties

PropertyDescription
$behaviorsarray – The behaviors that should be attached to this component.

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__get()Returns a property value, an event handler list or a behavior based on its name.
__isset()Checks if a property value is null.
__set()Sets value of a component property.
__unset()Sets a component property to be null.
asa()Returns the named behavior object.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attachEventHandler()Attaches an event handler to an event.
canGetProperty()Determines whether a property can be read.
canSetProperty()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()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
detachEventHandler()Detaches an existing event handler.
disableBehavior()Disables an attached behavior.
disableBehaviors()Disables all behaviors attached to this component.
doesTemplateExist()Returns whether a template exists.
enableBehavior()Enables an attached behavior.
enableBehaviors()Enables all behaviors attached to this component.
evaluateExpression()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 is set to true.
getEventHandlers()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()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()Determines whether an event is defined.
hasEventHandler()Checks whether the named event has attached handlers.
hasProperty()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()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

Arguments

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

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

Arguments

  • $name (string) – The name of the template.

Returns

boolean – 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 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:

  • 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

Arguments

  • $name (string) – The name of the template.

Returns

string, false – 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

Arguments

  • $inputName (string) – The input name.

Returns

string – 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 is set to true.

View source

Returns

string – 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

Returns

string

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

Returns

string

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

Returns

string – 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

Returns

mixed – The template that is being rendered.

Signature

public mixed getRenderingTemplate ( )

getScriptTag()

Wraps some Javascript code in a <script> tag.

View source

Arguments

Returns

string – The <script> tag.

Signature

public string getScriptTag ( $js )

getTemplateMode()

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

View source

Returns

string – Either 'site' or 'cp'.

Signature

public string getTemplateMode ( )

getTemplatesPath()

Returns the base path that templates should be found in.

View source

Returns

string

Signature

public string getTemplatesPath ( )

getTranslations()

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

View source

Returns

string – 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

Arguments

  • $loaderClass (string) – 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

Arguments

  • $hook (string) – The hook name.
  • $method (callback) – The callback function.

Returns

null

Signature

public null hook ( $hook, $method )

includeCss()

Prepares CSS for inclusion in the template.

View source

Arguments

  • $css (string) – The CSS.
  • $first (boolean) – Whether the CSS should be included before any other CSS that was already included with this method.

Returns

null

Signature

public null includeCss ( $css, $first = false )

includeCssFile()

Prepares a CSS file for inclusion in the template.

View source

Arguments

  • $url (string) – The URL to the CSS file.
  • $first (boolean) – Whether the CSS file should be included before any other CSS files that were already included with this method.

Returns

null

Signature

public null includeCssFile ( $url, $first = false )

includeCssResource()

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

View source

Arguments

  • $path (string) – The resource path to the CSS file.
  • $first (boolean) – Whether the CSS file should be included before any other CSS files that were already included with this method.

Returns

null

Signature

public null includeCssResource ( $path, $first = false )

includeFootHtml()

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

View source

Arguments

  • $node (string) – The HTML to be included in the template.
  • $first (boolean) – Whether the HTML should be included before any other HTML that was already included with this method.

Returns

null

Signature

public null includeFootHtml ( $node, $first = false )

includeFootNode()

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

View source

Arguments

  • $node (string) – The HTML to be included in the template.
  • $first (boolean) – 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

Arguments

  • $node (string) – The HTML to be included in the template.
  • $first (boolean) – Whether the HTML should be included before any other HTML that was already included with this method.

Returns

null

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

Arguments

  • $node (string) – The HTML to be included in the template.
  • $first (boolean) – Whether the HTML should be included before any other HTML that was already included with this method.

Returns

null

Signature

public null includeHeadNode ( $node, $first = false )

includeHiResCss()

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

View source

Arguments

  • $css (string) – The CSS.
  • $first (boolean) – Whether the CSS should be included before any other CSS that was already included with this method.

Returns

null

Signature

public null includeHiResCss ( $css, $first = false )

includeJs()

Prepares JS for inclusion in the template.

View source

Arguments

  • $js (string) – The Javascript code.
  • $first (boolean) – Whether the Javascript code should be included before any other Javascript code that was already included with this method.

Returns

null

Signature

public null includeJs ( $js, $first = false )

includeJsFile()

Prepares a JS file for inclusion in the template.

View source

Arguments

  • $url (string) – The URL to the JS file.
  • $first (boolean) – Whether the JS file should be included before any other JS files that were already included with this method.

Returns

null

Signature

public null includeJsFile ( $url, $first = false )

includeJsResource()

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

View source

Arguments

  • $path (string) – The resource path to the JS file.
  • $first (boolean) – Whether the JS file should be included before any other JS files that were already included with this method.

Returns

null

Signature

public null includeJsResource ( $path, $first = false )

includeTranslations()

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

View source

Returns

null

Signature

public null includeTranslations ( )

init()

Initializes the application component.

View source

Returns

null

Signature

public null init ( )

invokeHook()

Invokes a template hook. This is called by {@link Hook_Node {% hook %} tags).

View source

Arguments

  • $hook (string) – The hook name.
  • $context

Returns

string – Whatever the hooks returned.

Signature

public string invokeHook ( $hook, &$context )

isRendering()

Returns whether a template is currently being rendered.

View source

Returns

boolean – 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

Arguments

  • $inputId (string) – The input ID that should be namespaced.
  • $namespace (string) – The namespace. Defaults to the {@link getNamespace() active namespace}.

Returns

string – 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

Arguments

  • $inputName (string) – The input name that should be namespaced.
  • $namespace (string) – The namespace. Defaults to the {@link getNamespace() active namespace}.

Returns

string – 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

Arguments

  • $html (string) – The template with the inputs.
  • $namespace (string) – The namespace. Defaults to the {@link getNamespace() active namespace}.
  • $otherAttributes (boolean) – Whether id=, for=, etc., should also be namespaced. Defaults to true.

Returns

string – 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

Arguments

Returns

null

Signature

public null onPluginsLoaded ( Craft\Event $event )

render()

Renders a template.

View source

Arguments

  • $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 (boolean) – Whether to limit what's available to in the Twig context in the interest of security.

Returns

string – The rendered template.

Signature

public string render ( $template, $variables = [], $safeMode = false )

renderMacro()

Renders a macro within a given template.

View source

Arguments

  • $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.

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

Arguments

  • $template (string) – The source template string.
  • $object (mixed) – The object that should be passed into the template.
  • $safeMode (boolean) – Whether to limit what's available to in the Twig context in the interest of security.

Returns

string – The rendered template.

Signature

public string renderObjectTemplate ( $template, $object, $safeMode = false )

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.
  • $safeMode (boolean) – Whether to limit what's available to in the Twig context in the interest of security.

Returns

string – 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

Arguments

  • $namespace (string) – The new namespace.

Returns

null

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

Arguments

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

Returns

void

Throws

Signature

public void setTemplateMode ( $templateMode )

setTemplatesPath()

Sets the base path that templates should be found in.

View source

Arguments

Returns

void

Signature

public void setTemplatesPath ( $templatesPath )

startJsBuffer()

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 {@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

Returns

null

Signature

public null startJsBuffer ( )