You are here

protected function Renderer::ensureMarkupIsSafe in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Render/Renderer.php \Drupal\Core\Render\Renderer::ensureMarkupIsSafe()
  2. 9 core/lib/Drupal/Core/Render/Renderer.php \Drupal\Core\Render\Renderer::ensureMarkupIsSafe()

Escapes #plain_text or filters #markup as required.

Drupal uses Twig's auto-escape feature to improve security. This feature automatically escapes any HTML that is not known to be safe. Due to this the render system needs to ensure that all markup it generates is marked safe so that Twig does not do any additional escaping.

By default all #markup is filtered to protect against XSS using the admin tag list. Render arrays can alter the list of tags allowed by the filter using the #allowed_tags property. This value should be an array of tags that Xss::filter() would accept. Render arrays can escape text instead of XSS filtering by setting the #plain_text property instead of #markup. If #plain_text is used #allowed_tags is ignored.

Parameters

array $elements: A render array with #markup set.

Return value

\Drupal\Component\Render\MarkupInterface|string The escaped markup wrapped in a Markup object. If $elements['#markup'] is an instance of \Drupal\Component\Render\MarkupInterface, it won't be escaped or filtered again.

See also

\Drupal\Component\Utility\Html::escape()

\Drupal\Component\Utility\Xss::filter()

\Drupal\Component\Utility\Xss::filterAdmin()

File

core/lib/Drupal/Core/Render/Renderer.php, line 728

Class

Renderer
Turns a render array into an HTML string.

Namespace

Drupal\Core\Render

Code

protected function ensureMarkupIsSafe(array $elements) {
  if (isset($elements['#plain_text'])) {
    $elements['#markup'] = Markup::create(Html::escape($elements['#plain_text']));
  }
  elseif (!$elements['#markup'] instanceof MarkupInterface) {

    // The default behavior is to XSS filter using the admin tag list.
    $tags = $elements['#allowed_tags'] ?? Xss::getAdminTagList();
    $elements['#markup'] = Markup::create(Xss::filter($elements['#markup'], $tags));
  }
  return $elements;
}