Back to ScriptsRenderer class

Method renderAttributes

private string
renderAttributes
(array $attributes)
Renders the element attributes
Parameters
  • array $attributes The element attributes
Returns
  • string The attributes string
Since
  • 4.0.0

Method renderAttributes - Source code

/**
 * Renders the element attributes
 *
 * @param   array  $attributes  The element attributes
 *
 * @return  string  The attributes string
 *
 * @since   4.0.0
 */
private function renderAttributes(array $attributes) : string
{
    $buffer = '';
    $defaultJsMimes = array('text/javascript', 'application/javascript', 'text/x-javascript', 'application/x-javascript');
    $html5NoValueAttributes = array('defer', 'async', 'nomodule');
    foreach ($attributes as $attrib => $value) {
        // Don't add the 'options' attribute. This attribute is for internal use (version, conditional, etc).
        if ($attrib === 'options' || $attrib === 'src') {
            continue;
        }
        // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
        if (\in_array($attrib, array('type', 'mime')) && $this->_doc->isHtml5() && \in_array($value, $defaultJsMimes)) {
            continue;
        }
        // B/C: If defer and async is false or empty don't render the attribute. Also skip if value is bool:false.
        if (\in_array($attrib, array('defer', 'async')) && !$value || $value === false) {
            continue;
        }
        // NoValue attribute, if it have bool:true
        $isNoValueAttrib = $value === true || \in_array($attrib, $html5NoValueAttributes);
        // Don't add type attribute if document is HTML5 and it's a default mime type. 'mime' is for B/C.
        if ($attrib === 'mime') {
            $attrib = 'type';
        } elseif ($isNoValueAttrib) {
            $value = $attrib;
        }
        // Add attribute to script tag output.
        $buffer .= ' ' . htmlspecialchars($attrib, ENT_COMPAT, 'UTF-8');
        if (!($this->_doc->isHtml5() && $isNoValueAttrib)) {
            // Json encode value if it's an array.
            $value = !is_scalar($value) ? json_encode($value) : $value;
            $buffer .= '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"';
        }
    }
    return $buffer;
}