Attributes built via the Attribute
class are escaped.
The Attribute::__toString()
code is the following one.
$return = '';
/** @var \Drupal\Core\Template\AttributeValueBase $value */
foreach ($this->storage as $name => $value) {
$rendered = $value->render();
if ($rendered) {
$return .= ' ' . $rendered;
}
}
return $return;
In a class that extend AttributeValueBase
, for example AttributeString
, render()
contains the following code.
value = (string) $this;
if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
return Html::escape($this->name) . '="' . $value . '"';
}
AttributeString::__toString()
contains the following code.
return Html::escape($this->value);
Html::escape()
is called for the attribute name and its value. That's why an attribute built using code similar to the following one single quotes inside the attribute name and value are escaped.
$attributes = new Attribute(array());
$attributes['id'] = 'socks';
$attributes['style'] = 'background-color:white';
echo '<cat ' . $attributes . '>';
AttributeArray::__toString()
uses the following code.
// Filter out any empty values before printing.
$this->value = array_unique(array_filter($this->value));
return Html::escape(implode(' ', $this->value));
This means that for an attribute built using code similar to the following one, the attribute value is escaped.
$attributes = new Attribute();
$attributes['class'] = array();
$attributes['class'][] = 'cat';