You are here

public static function HtmlTag::preRenderHtmlTag in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Render/Element/HtmlTag.php \Drupal\Core\Render\Element\HtmlTag::preRenderHtmlTag()

Pre-render callback: Renders a generic HTML tag with attributes.


array $element: An associative array containing:

  • #tag: The tag name to output. Typical tags added to the HTML HEAD:

    • meta: To provide meta information, such as a page refresh.
    • link: To refer to stylesheets and other contextual information.
    • script: To load JavaScript.

    The value of #tag is escaped.

  • #attributes: (optional) An array of HTML attributes to apply to the tag. The attributes are escaped, see \Drupal\Core\Template\Attribute.
  • #value: (optional) A string containing tag content, such as inline CSS. The value of #value will be XSS admin filtered if it is not safe.
  • #noscript: (optional) If TRUE, the markup (including any prefix or suffix) will be wrapped in a <noscript> element. (Note that passing any non-empty value here will add the <noscript> tag.)

Return value


1 call to HtmlTag::preRenderHtmlTag()
HtmlTagTest::testPreRenderHtmlTag in core/tests/Drupal/Tests/Core/Render/Element/HtmlTagTest.php
@covers ::preRenderHtmlTag @dataProvider providerPreRenderHtmlTag


core/lib/Drupal/Core/Render/Element/HtmlTag.php, line 82


Provides a render element for any HTML tag, with properties and value.




public static function preRenderHtmlTag($element) {
  $attributes = isset($element['#attributes']) ? new Attribute($element['#attributes']) : '';

  // An HTML tag should not contain any special characters. Escape them to
  // ensure this cannot be abused.
  $escaped_tag = HtmlUtility::escape($element['#tag']);
  $open_tag = '<' . $escaped_tag . $attributes;
  $close_tag = '</' . $escaped_tag . ">\n";

  // Construct a void element.
  if (in_array($element['#tag'], self::$voidElements)) {
    $open_tag .= ' />';
    $close_tag = "\n";
  else {
    $open_tag .= '>';
    $markup = $element['#value'] instanceof MarkupInterface ? $element['#value'] : Xss::filterAdmin($element['#value']);
    $element['#markup'] = Markup::create($markup);
  $prefix = isset($element['#prefix']) ? $element['#prefix'] . $open_tag : $open_tag;
  $suffix = isset($element['#suffix']) ? $close_tag . $element['#suffix'] : $close_tag;
  if (!empty($element['#noscript'])) {
    $prefix = '<noscript>' . $prefix;
    $suffix .= '</noscript>';
  $element['#prefix'] = Markup::create($prefix);
  $element['#suffix'] = Markup::create($suffix);
  return $element;