You are here

function theme_render_and_autoescape in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/includes/theme.inc \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

Parameters

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.

Throws

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

See also

\Drupal\Core\Template\TwigExtension::escapeFilter()

3 calls to theme_render_and_autoescape()
nyan_cat_render_template in core/modules/system/tests/themes/engines/nyan_cat/nyan_cat.engine
Implements hook_render_template().
ThemeRenderAndAutoescapeTest::testThemeEscapeAndRenderNotPrintable in core/tests/Drupal/KernelTests/Core/Theme/ThemeRenderAndAutoescapeTest.php
Ensures invalid content is handled correctly.
ThemeRenderAndAutoescapeTest::testThemeRenderAndAutoescape in core/tests/Drupal/KernelTests/Core/Theme/ThemeRenderAndAutoescapeTest.php
@dataProvider providerTestThemeRenderAndAutoescape

File

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

Code

function theme_render_and_autoescape($arg) {
  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;
    }
    elseif (method_exists($arg, 'toString')) {
      $return = $arg
        ->toString();
    }
    else {
      throw new \Exception(t('Object of type "@class" cannot be printed.', array(
        '@class' => get_class($arg),
      )));
    }
  }

  // We have a string or an object converted to a string: Escape it!
  if (isset($return)) {
    return SafeMarkup::isSafe($return, 'html') ? $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);
}