TemplatesService

Packagecraft.app.services
NamespaceCraft
Inheritanceclass TemplatesService » BaseApplicationComponent » \CApplicationComponent » \CComponent
Implements\IApplicationComponent
Since1.0
Source Codecraft/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 #

PropertyTypeDescriptionDefined By
behaviorsarraythe behaviors that should be attached to this component.\CApplicationComponent
csrfInputstringReturns the HTML for the CSRF hidden input token. Used for when the config setting enableCsrfValidation is set to true.TemplatesService
footHtmlstringReturns the HTML prepared for inclusion right above the </body> in the template, and flushes out the foot HTML queue.TemplatesService
headHtmlstringReturns the HTML prepared for inclusion in the <head> of the template, and flushes out the head HTML queue.TemplatesService
isInitializedboolChecks if this application component has been initialized.\CApplicationComponent
namespacestringReturns the active namespace.TemplatesService
renderingTemplatemixedReturns the template path that is currently being rendered, or the full template if renderString() or renderObjectTemplate() was called.TemplatesService
templateModestringReturns the current template mode (either 'site' or 'cp').TemplatesService
templatesPathstringReturns the base path that templates should be found in.TemplatesService
translationsstringReturns the translations prepared for inclusion by includeTranslations(), in JSON, and flushes out the translations queue.TemplatesService
twigTwigEnvironmentReturns the Twig Environment instance for a given template loader class.TemplatesService

Public Methods #

MethodDescriptionDefined 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 #

EventDescriptionDefined By
onPluginsLoadedLoads plugin-supplied Twig extensions now that all plugins have been loaded.TemplatesService

Property Details #

csrfInput #

read-only
public string getCsrfInput()

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

footHtml #

read-only
public string 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 UserSessionService::addJsResourceFlash()
  • Any Javascript included in the previous request using UserSessionService::addJsFlash()
  • Any Javascript files included using includeJsFile() or includeJsResource()
  • Any Javascript code included using includeJs()
  • Any HTML included using includeFootHtml()

headHtml #

read-only
public string 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 includeCssFile() or includeCssResource()
  • Any CSS included using includeCss() or includeHiResCss()
  • Any HTML included using includeHeadHtml()

namespace #

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

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.

renderingTemplate #

read-only
public mixed getRenderingTemplate()

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

templateMode #

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

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

templatesPath #

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

Returns the base path that templates should be found in.

translations #

read-only
public string getTranslations()

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

twig #

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

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

Method Details #

clearJsBuffer() #

public function clearJsBuffer($scriptTag = true)
{
     if (count($this->_jsBuffers) <= 1)
     {
          return false;
     }

     $buffer = array_pop($this->_jsBuffers);

     if ($buffer)
     {
          $js = $this->_combineJs($buffer);

          if ($scriptTag)
          {
               return $this->getScriptTag($buffer);
          }
          else
          {
               return $js;
          }
     }
}
$scriptTagboolWhether the Javascript code should be wrapped in a <script> tag. Defaults to true.
Returnsstring / 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.

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

doesTemplateExist() #

public function doesTemplateExist($name)
{
     try
     {
          return (bool) $this->findTemplate($name);
     }
     catch (\Twig_Error_Loader $e)
     {
          // _validateTemplateName() han an issue with it
          return false;
     }
}
$namestringThe name of the template.
Returnsbool

Whether the template exists.

Returns whether a template exists.

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

findTemplate() #

public function findTemplate($name)
{
     // Normalize the template name
     $name = trim(preg_replace('#/{2,}#', '/', strtr($name, '\\', '/')), '/');

     $key = $this->_templatesPath.':'.$name;

     // Is this template path already cached?
     if (isset($this->_templatePaths[$key]))
     {
          return $this->_templatePaths[$key];
     }

     // Validate the template name
     $this->_validateTemplateName($name);

     // Look for the template in the main templates folder
     $basePaths = array();

     // Should we be looking for a localized version of the template?
     if (craft()->request->isSiteRequest() && IOHelper::folderExists($this->_templatesPath.craft()->language))
     {
          $basePaths[] = $this->_templatesPath.craft()->language.'/';
     }

     $basePaths[] = $this->_templatesPath;

     foreach ($basePaths as $basePath)
     {
          if (($path = $this->_findTemplate($basePath, $name)) !== null)
          {
               return $this->_templatePaths[$key] = $path;
          }
     }

     // Otherwise maybe it's a plugin template?

     // Only attempt to match against a plugin's templates if this is a CP or action request.
     if ($this->getTemplateMode() === TemplateMode::CP || craft()->request->isActionRequest())
     {
          // Sanitize
          $name = craft()->request->decodePathInfo($name);

          $parts = array_filter(explode('/', $name));
          $pluginHandle = StringHelper::toLowerCase(array_shift($parts));

          if ($pluginHandle && ($plugin = craft()->plugins->getPlugin($pluginHandle)) !== null)
          {
               // Get the template path for the plugin.
               $basePath = craft()->path->getPluginsPath().StringHelper::toLowerCase($plugin->getClassHandle()).'/templates/';

               // Get the new template name to look for within the plugin's templates folder
               $tempName = implode('/', $parts);

               if (($path = $this->_findTemplate($basePath, $tempName)) !== null)
               {
                    return $this->_templatePaths[$key] = $path;
               }
          }
     }

     return false;
}
$namestringThe name of the template.
Returnsstring / false

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

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

formatInputId() #

public function formatInputId($inputName)
{
     return rtrim(preg_replace('/[\[\]]+/', '-', $inputName), '-');
}
$inputNamestringThe input name.
Returnsstring

The input ID.

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

getCsrfInput() #

public function getCsrfInput()
{
     if (craft()->config->get('enableCsrfProtection') === true)
     {
          return '<input type="hidden" name="'.craft()->config->get('csrfTokenName').'" value="'.craft()->request->getCsrfToken().'">';
     }

     return '';
}
Returnsstring

If 'enabledCsrfProtection' is enabled, the HTML for the hidden input, otherwise an empty string.

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

getFootHtml() #

public function getFootHtml()
{
     if (craft()->isInstalled() && craft()->request->isCpRequest())
     {
          // Include any JS/resource flashes
          foreach (craft()->userSession->getJsResourceFlashes() as $path)
          {
               $this->includeJsResource($path);
          }

          foreach (craft()->userSession->getJsFlashes() as $js)
          {
               $this->includeJs($js, true);
          }
     }

     // Are there any JS files to include?
     if (!empty($this->_jsFiles))
     {
          foreach($this->_jsFiles as $url)
          {
               $node = '<script type="text/javascript" src="'.$url.'"></script>';
               $this->includeFootHtml($node);
          }

          $this->_jsFiles = array();
     }

     // Is there any JS to include?
     foreach ($this->_jsBuffers as $buffer)
     {
          if ($buffer)
          {
               $this->includeFootHtml($this->getScriptTag($buffer));
          }
     }

     $this->_jsBuffers = array(array());

     if (!empty($this->_footHtml))
     {
          $footNodes = implode("\n", $this->_footHtml);
          $this->_footHtml = array();
          return $footNodes;
     }
}
Returnsstring

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 UserSessionService::addJsResourceFlash()
  • Any Javascript included in the previous request using UserSessionService::addJsFlash()
  • Any Javascript files included using includeJsFile() or includeJsResource()
  • Any Javascript code included using includeJs()
  • Any HTML included using includeFootHtml()

getHeadHtml() #

public function getHeadHtml()
{
     // Are there any CSS files to include?
     if (!empty($this->_cssFiles))
     {
          foreach ($this->_cssFiles as $url)
          {
               $node = HtmlHelper::encodeParams('<link rel="stylesheet" type="text/css" href="{url}"/>', array('url' => $url));
               $this->includeHeadHtml($node);
          }

          $this->_cssFiles = array();
     }

     // Is there any hi-res CSS to include?
     if (!empty($this->_hiResCss))
     {
          $this->includeCss("@media only screen and (-webkit-min-device-pixel-ratio: 1.5),\n" .
               "only screen and (   -moz-min-device-pixel-ratio: 1.5),\n" .
               "only screen and (     -o-min-device-pixel-ratio: 3/2),\n" .
               "only screen and (        min-device-pixel-ratio: 1.5),\n" .
               "only screen and (        min-resolution: 1.5dppx){\n" .
               implode("\n\n", $this->_hiResCss)."\n" .
          '}');

          $this->_hiResCss = array();
     }

     // Is there any CSS to include?
     if (!empty($this->_css))
     {
          $css = implode("\n\n", $this->_css);
          $node = "<style type=\"text/css\">\n".$css."\n</style>";
          $this->includeHeadHtml($node);

          $this->_css = array();
     }

     if (!empty($this->_headHtml))
     {
          $headNodes = implode("\n", $this->_headHtml);
          $this->_headHtml = array();
          return $headNodes;
     }
}
Returnsstring

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 includeCssFile() or includeCssResource()
  • Any CSS included using includeCss() or includeHiResCss()
  • Any HTML included using includeHeadHtml()

getNamespace() #

public function getNamespace()
{
     return $this->_namespace;
}
Returnsstring

The namespace.

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.

getRenderingTemplate() #

public function getRenderingTemplate()
{
     if ($this->isRendering())
     {
          if (strncmp($this->_renderingTemplate, 'string:', 7) === 0)
          {
               $template = $this->_renderingTemplate;
          }
          else
          {
               $template = $this->findTemplate($this->_renderingTemplate);

               if (!$template)
               {
                    $template = $this->_templatesPath.$this->_renderingTemplate;
               }
          }

          return $template;
     }
}
Returnsmixed

The template that is being rendered.

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

getScriptTag() #

public function getScriptTag($js)
{
     if (is_array($js))
     {
          $js = $this->_combineJs($js);
     }

     return "<script type=\"text/javascript\">\n/*<![CDATA[*/\n".$js."\n/*]]>*/\n</script>";
}
$jsstring / arrayThe Javascript code.
Returnsstring

The <script> tag.

Wraps some Javascript code in a <script> tag.

getTemplateMode() #

public function getTemplateMode()
{
     return $this->_templateMode;
}
Returnsstring

Either 'site' or 'cp'.

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

getTemplatesPath() #

public function getTemplatesPath()
{
     return $this->_templatesPath;
}
Returnsstring

Returns the base path that templates should be found in.

getTranslations() #

public function getTranslations()
{
     $translations = JsonHelper::encode(array_filter($this->_translations));
     $this->_translations = array();
     return $translations;
}
Returnsstring

A JSON-encoded array of source/translation message mappings.

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

getTwig() #

public function getTwig($loaderClass = null, $options = array())
{
     if (!$loaderClass)
     {
          $loaderClass = __NAMESPACE__.'\\TemplateLoader';
     }

     $options = array_merge(array('safe_mode' => false), $options);

     $cacheKey = $this->getTemplateMode().':'.$loaderClass.':'.md5(serialize($options));

     if (!isset($this->_twigs[$cacheKey]))
     {
          $loader = new $loaderClass();
          $options = array_merge($this->_getTwigOptions(), $options);

          $twig = new TwigEnvironment($loader, $options);

          $twig->addExtension(new \Twig_Extension_StringLoader());
          $twig->addExtension(new CraftTwigExtension($twig));

          if (craft()->config->get('devMode'))
          {
               $twig->addExtension(new \Twig_Extension_Debug());
          }

          // Set our timezone
          $timezone = craft()->getTimeZone();
          $twig->getExtension('core')->setTimezone($timezone);

          // Set our custom parser to support "include" tags using the capture mode
          $twig->setParser(new TwigParser($twig));

          $this->_twigs[$cacheKey] = $twig;

          // Give plugins a chance to add their own Twig extensions
          $this->_addPluginTwigExtensions($twig);
     }

     return $this->_twigs[$cacheKey];
}
$loaderClassstringThe 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
ReturnsTwigEnvironment

The Twig Environment instance.

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

hook() #

public function hook($hook, $method)
{
     $this->_hooks[$hook][] = $method;
}
$hookstringThe hook name.
$methodcallbackThe callback function.

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.

includeCss() #

public function includeCss($css, $first = false)
{
     ArrayHelper::prependOrAppend($this->_css, trim($css), $first);
}
$cssstringThe CSS.
$firstboolWhether the CSS should be included before any other CSS that was already included with this method.

Prepares CSS for inclusion in the template.

includeCssFile() #

public function includeCssFile($url, $first = false)
{
     if (!in_array($url, $this->_cssFiles))
     {
          ArrayHelper::prependOrAppend($this->_cssFiles, $url, $first);
     }
}
$urlstringThe URL to the CSS file.
$firstboolWhether the CSS file should be included before any other CSS files that were already included with this method.

Prepares a CSS file for inclusion in the template.

includeCssResource() #

public function includeCssResource($path, $first = false)
{
     $url = UrlHelper::getResourceUrl($path);
     $this->includeCssFile($url, $first);
}
$pathstringThe resource path to the CSS file.
$firstboolWhether the CSS file should be included before any other CSS files that were already included with this method.

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

includeFootHtml() #

public function includeFootHtml($node, $first = false)
{
     ArrayHelper::prependOrAppend($this->_footHtml, $node, $first);
}
$nodestringThe HTML to be included in the template.
$firstboolWhether the HTML should be included before any other HTML that was already included with this method.

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

includeFootNode() #

public function includeFootNode($node, $first = false)
{
     craft()->deprecator->log('TemplatesService::includeFootNode()', 'TemplatesService::includeFootNode() has been deprecated. Use includeFootHtml() instead.');
     $this->includeFootHtml($node, $first);
}
$nodestringThe HTML to be included in the template.
$firstboolWhether the HTML should be included before any other HTML that was already included with this method.

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

includeHeadHtml() #

public function includeHeadHtml($node, $first = false)
{
     ArrayHelper::prependOrAppend($this->_headHtml, $node, $first);
}
$nodestringThe HTML to be included in the template.
$firstboolWhether the HTML should be included before any other HTML that was already included with this method.

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

includeHeadNode() #

public function includeHeadNode($node, $first = false)
{
     craft()->deprecator->log('TemplatesService::includeHeadNode()', 'TemplatesService::includeHeadNode() has been deprecated. includeHeadHtml() instead.');
     $this->includeHeadHtml($node, $first);
}
$nodestringThe HTML to be included in the template.
$firstboolWhether the HTML should be included before any other HTML that was already included with this method.

Deprecated in 1.1. Use includeHeadHtml() instead.

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

includeHiResCss() #

public function includeHiResCss($css, $first = false)
{
     ArrayHelper::prependOrAppend($this->_hiResCss, trim($css), $first);
}
$cssstringThe CSS.
$firstboolWhether the CSS should be included before any other CSS that was already included with this method.

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

includeJs() #

public function includeJs($js, $first = false)
{
     // Trim any whitespace and ensure it ends with a semicolon.
     $js = trim($js, " \t\n\r\0\x0B;").';';

     $latestBuffer =& $this->_jsBuffers[count($this->_jsBuffers)-1];
     ArrayHelper::prependOrAppend($latestBuffer, $js, $first);
}
$jsstringThe Javascript code.
$firstboolWhether the Javascript code should be included before any other Javascript code that was already included with this method.

Prepares JS for inclusion in the template.

includeJsFile() #

public function includeJsFile($url, $first = false)
{
     if (!in_array($url, $this->_jsFiles))
     {
          ArrayHelper::prependOrAppend($this->_jsFiles, $url, $first);
     }
}
$urlstringThe URL to the JS file.
$firstboolWhether the JS file should be included before any other JS files that were already included with this method.

Prepares a JS file for inclusion in the template.

includeJsResource() #

public function includeJsResource($path, $first = false)
{
     $url = UrlHelper::getResourceUrl($path);
     $this->includeJsFile($url, $first);
}
$pathstringThe resource path to the JS file.
$firstboolWhether the JS file should be included before any other JS files that were already included with this method.

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

includeTranslations() #

public function includeTranslations()
{
     $messages = func_get_args();

     foreach ($messages as $message)
     {
          if (!array_key_exists($message, $this->_translations))
          {
               $translation = Craft::t($message);

               if ($translation != $message)
               {
                    $this->_translations[$message] = $translation;
               }
               else
               {
                    $this->_translations[$message] = null;
               }
          }
     }
}

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

init() #

public function init()
{
     // Set the initial template mode based on whether this is a CP or Site request
     if (craft()->request->isCpRequest())
     {
          $this->setTemplateMode(TemplateMode::CP);
     }
     else
     {
          $this->setTemplateMode(TemplateMode::Site);
     }

     // Register the cp.elements.element hook
     $this->hook('cp.elements.element', array($this, '_getCpElementHtml'));
}

Initializes the application component.

invokeHook() #

public function invokeHook($hook, &$context)
{
     $return = '';

     if (isset($this->_hooks[$hook]))
     {
          foreach ($this->_hooks[$hook] as $method)
          {
               $return .= call_user_func_array($method, array(&$context));
          }
     }

     return $return;
}
$hookstringThe hook name.
&$contextarrayThe current template context.
Returnsstring

Whatever the hooks returned.

Invokes a template hook.

This is called by {% hook % tags).

isRendering() #

public function isRendering()
{
     return isset($this->_renderingTemplate);
}
Returnsbool

Whether a template is currently being rendered.

Returns whether a template is currently being rendered.

namespaceInputId() #

public function namespaceInputId($inputId, $namespace = null)
{
     if ($namespace === null)
     {
          $namespace = $this->getNamespace();
     }

     if ($namespace)
     {
          $inputId = $this->formatInputId($namespace).'-'.$inputId;
     }

     return $inputId;
}
$inputIdstringThe input ID that should be namespaced.
$namespacestringThe namespace. Defaults to the active namespace.
Returnsstring

The namespaced input ID.

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.

namespaceInputName() #

public function namespaceInputName($inputName, $namespace = null)
{
     if ($namespace === null)
     {
          $namespace = $this->getNamespace();
     }

     if ($namespace)
     {
          $inputName = preg_replace('/([^\'"\[\]]+)([^\'"]*)/', $namespace.'[$1]$2', $inputName);
     }

     return $inputName;
}
$inputNamestringThe input name that should be namespaced.
$namespacestringThe namespace. Defaults to the active namespace.
Returnsstring

The namespaced input name.

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.

namespaceInputs() #

public function namespaceInputs($html, $namespace = null, $otherAttributes = true)
{
     if (!is_string($html) || $html === '')
     {
          return '';
     }

     if ($namespace === null)
     {
          $namespace = $this->getNamespace();
     }

     if ($namespace)
     {
          // Protect the textarea content
          $this->_textareaMarkers = array();
          $html = preg_replace_callback('/(<textarea\b[^>]*>)(.*?)(<\/textarea>)/is', array($this, '_createTextareaMarker'), $html);

          // name= attributes
          $html = preg_replace('/(?<![\w\-])(name=(\'|"))([^\'"\[\]]+)([^\'"]*)\2/i', '$1'.$namespace.'[$3]$4$2', $html);

          // id= and for= attributes
          if ($otherAttributes)
          {
               $idNamespace = $this->formatInputId($namespace);
               $html = preg_replace('/(?<![\w\-])((id|for|list|aria\-labelledby|data\-target|data\-reverse\-target|data\-target\-prefix)=(\'|")#?)([^\.\'"][^\'"]*)\3/i', '$1'.$idNamespace.'-$4$3', $html);
          }

          // Bring back the textarea content
          $html = str_replace(array_keys($this->_textareaMarkers), array_values($this->_textareaMarkers), $html);
     }

     return $html;
}
$htmlstringThe template with the inputs.
$namespacestringThe namespace. Defaults to the active namespace.
$otherAttributesboolWhether id=, for=, etc., should also be namespaced. Defaults to true.
Returnsstring

The HTML with namespaced input names.

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">

onPluginsLoaded() #

public function onPluginsLoaded(Event $event)
{
     foreach ($this->_twigs as $twig)
     {
          $this->_addPluginTwigExtensions($twig);
     }
}
$eventEvent

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

render() #

public function render($template, $variables = array(), $safeMode = false)
{
     $safeMode = $this->_useSafeMode($safeMode);
     $twig = $this->getTwig(null, array('safe_mode' => $safeMode));

     $lastRenderingTemplate = $this->_renderingTemplate;
     $this->_renderingTemplate = $template;

     try
     {
          $result = $twig->render($template, $variables);
     }
     catch (\RuntimeException $e)
     {
          if (!craft()->config->get('devMode'))
          {
               // Throw a generic exception instead
               throw new Exception(Craft::t('An error occurred when rendering a template.'), 0, $e);
          }
          else
          {
               throw $e;
          }
     }

     $this->_renderingTemplate = $lastRenderingTemplate;
     return $result;
}
$templatemixedThe name of the template to load, or a StringTemplate object.
$variablesarrayThe variables that should be available to the template.
$safeModeboolWhether to limit what's available to in the Twig context in the interest of security.
Returnsstring

The rendered template.

Renders a template.

renderMacro() #

public function renderMacro($template, $macro, $args = array())
{
     $twig = $this->getTwig();
     $twigTemplate = $twig->loadTemplate($template);

     $lastRenderingTemplate = $this->_renderingTemplate;
     $this->_renderingTemplate = $template;

     try
     {
          $result = call_user_func_array(array($twigTemplate, 'get'.$macro), $args);
     }
     catch (\RuntimeException $e)
     {
          if (!craft()->config->get('devMode'))
          {
               // Throw a generic exception instead
               throw new Exception(Craft::t('An error occurred when rendering a template.'), 0, $e);
          }
          else
          {
               throw $e;
          }
     }

     $this->_renderingTemplate = $lastRenderingTemplate;

     return (string) $result;
}
$templatestringThe name of the template the macro lives in.
$macrostringThe name of the macro.
$argsarrayAny arguments that should be passed to the macro.
Returnsstring

The rendered macro output.

Renders a macro within a given template.

renderObjectTemplate() #

public function renderObjectTemplate($template, $object, $safeMode = false)
{
     $safeMode = $this->_useSafeMode($safeMode);

     // If there are no dynamic tags, just return the template
     if (strpos($template, '{') === false)
     {
          return $template;
     }

     try
     {
          // Get a Twig instance with the String template loader
          $twig = $this->getTwig('Twig_Loader_String', array('safe_mode' => $safeMode));

          // Have we already parsed this template?
          $cacheKey = $template.':'.($safeMode ? 'safe' : 'unsafe');

          if (!isset($this->_objectTemplates[$cacheKey]))
          {
               // Replace shortcut "{var}"s with "{{object.var}}"s, without affecting normal Twig tags
               $formattedTemplate = preg_replace('/(?<![\{\%])\{(?![\{\%])/', '{{object.', $template);
               $formattedTemplate = preg_replace('/(?<![\}\%])\}(?![\}\%])/', '|raw}}', $formattedTemplate);
               $this->_objectTemplates[$cacheKey] = $twig->loadTemplate($formattedTemplate);
          }

          // Temporarily disable strict variables if it's enabled
          $strictVariables = $twig->isStrictVariables();

          if ($strictVariables)
          {
               $twig->disableStrictVariables();
          }

          // Render it!
          $lastRenderingTemplate = $this->_renderingTemplate;
          $this->_renderingTemplate = 'string:'.$template;
          $result = $this->_objectTemplates[$cacheKey]->render(array(
               'object' => $object
          ));

          $this->_renderingTemplate = $lastRenderingTemplate;

          // Re-enable strict variables
          if ($strictVariables)
          {
               $twig->enableStrictVariables();
          }
     }
     catch (\RuntimeException $e)
     {
          if (!craft()->config->get('devMode'))
          {
               // Throw a generic exception instead
               throw new Exception(Craft::t('An error occurred when rendering a template.'), 0, $e);
          }
          else
          {
               throw $e;
          }
     }

     return $result;
}
$templatestringThe source template string.
$objectmixedThe object that should be passed into the template.
$safeModeboolWhether to limit what's available to in the Twig context in the interest of security.
Returnsstring

The rendered template.

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.

renderString() #

public function renderString($template, $variables = array(), $safeMode = false)
{
     $safeMode = $this->_useSafeMode($safeMode);
     $stringTemplate = new StringTemplate(md5($template), $template);

     $lastRenderingTemplate = $this->_renderingTemplate;
     $this->_renderingTemplate = 'string:'.$template;
     $result = $this->render($stringTemplate, $variables, $safeMode);
     $this->_renderingTemplate = $lastRenderingTemplate;

     return $result;
}
$templatestringThe source template string.
$variablesarrayAny variables that should be available to the template.
$safeModeboolWhether to limit what's available to in the Twig context in the interest of security.
Returnsstring

The rendered template.

Renders a template defined in a string.

setNamespace() #

public function setNamespace($namespace)
{
     $this->_namespace = $namespace;
}
$namespacestringThe new namespace.

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.

setTemplateMode() #

public function setTemplateMode($templateMode)
{
     // Validate
     if (!in_array($templateMode, array(TemplateMode::Site, TemplateMode::CP)))
     {
          throw new Exception('"'.$templateMode.'" is not a valid template mode');
     }

     // Set the new template mode
     $this->_templateMode = $templateMode;

     // Update everything
     $pathsService = craft()->path;

     if ($templateMode == TemplateMode::CP)
     {
          $this->setTemplatesPath($pathsService->getCpTemplatesPath());
          $this->_defaultTemplateExtensions = array('html', 'twig');
          $this->_indexTemplateFilenames = array('index');
     }
     else
     {
          $this->setTemplatesPath($pathsService->getSiteTemplatesPath());
          $this->_defaultTemplateExtensions = craft()->config->get('defaultTemplateExtensions');
          $this->_indexTemplateFilenames = craft()->config->get('indexTemplateFilenames');
     }
}
$templateModestringEither 'site' or 'cp'
Returnsvoid

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

setTemplatesPath() #

public function setTemplatesPath($templatesPath)
{
     $this->_templatesPath = rtrim($templatesPath, '/').'/';
}
$templatesPathstring
Returnsvoid

Sets the base path that templates should be found in.

startJsBuffer() #

public function startJsBuffer()
{
     $this->_jsBuffers[] = array();
}

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.