/Drupal 8

function theme_render_and_autoescape


Escapes and renders variables for theme functions.

This method is used in theme functions to ensure that the result is safe for output inside HTML fragments. This mimics the behavior of the auto-escape functionality in Twig.

Note: This function should be kept in sync with \Drupal\Core\Template\TwigExtension::escapeFilter().

@todo Discuss deprecating this in https://www.drupal.org/node/2575081. @todo Refactor this to keep it in sync with Twig filtering in https://www.drupal.org/node/2575065


mixed $arg: The string, object, or render array to escape if needed.

Return value

string The rendered string, safe for use in HTML. The string is not safe when used as any part of an HTML attribute name or value.


\Exception Thrown when an object is passed in which cannot be printed.

See also



core/includes/theme.inc, line 404
The theme system, which controls the output of Drupal.


function theme_render_and_autoescape($arg) {
  // If it's a renderable, then it'll be up to the generated render array it
  // returns to contain the necessary cacheability & attachment metadata. If
  // it doesn't implement CacheableDependencyInterface or AttachmentsInterface
  // then there is nothing to do here.
  if (!($arg instanceof RenderableInterface) && ($arg instanceof CacheableDependencyInterface || $arg instanceof AttachmentsInterface)) {
    $arg_bubbleable = [];

  if ($arg instanceof MarkupInterface) {
    return (string) $arg;
  $return = NULL;

  if (is_scalar($arg)) {
    $return = (string) $arg;
  elseif (is_object($arg)) {
    if ($arg instanceof RenderableInterface) {
      $arg = $arg->toRenderable();
    elseif (method_exists($arg, '__toString')) {
      $return = (string) $arg;
    // You can't throw exceptions in the magic PHP __toString methods, see
    // http://php.net/manual/language.oop5.magic.php#object.tostring so
    // we also support a toString method.
    elseif (method_exists($arg, 'toString')) {
      $return = $arg->toString();
    else {
      throw new \Exception('Object of type ' . get_class($arg) . ' cannot be printed.');

  // We have a string or an object converted to a string: Escape it!
  if (isset($return)) {
    return $return instanceof MarkupInterface ? $return : Html::escape($return);

  // This is a normal render array, which is safe by definition, with special
  // simple cases already handled.

  // Early return if this element was pre-rendered (no need to re-render).
  if (isset($arg['#printed']) && $arg['#printed'] == TRUE && isset($arg['#markup']) && strlen($arg['#markup']) > 0) {
    return (string) $arg['#markup'];
  $arg['#printed'] = FALSE;
  return (string) \Drupal::service('renderer')->render($arg);

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.