Skip to content
Snippets Groups Projects

Merge component ['#attributes'] with the ['#props']['attributes'].

Files
2
@@ -6,6 +6,7 @@
use Drupal\Core\Render\Component\Exception\InvalidComponentDataException;
use Drupal\Core\Render\Element;
use Drupal\Core\Security\DoTrustedCallbackTrait;
use Drupal\Core\Template\Attribute;
/**
* Provides a Single-Directory Component render element.
@@ -55,6 +56,8 @@ class ComponentElement extends RenderElementBase {
* @throws \Drupal\Core\Render\Component\Exception\InvalidComponentDataException
*/
public function preRenderComponent(array $element): array {
$this->mergeElementAttributesToPropAttributes($element);
$props = $element['#props'];
if (isset($element["#variant"]) && !isset($props['variant'])) {
$props['variant'] = $element["#variant"];
@@ -91,6 +94,7 @@ public function preRenderComponent(array $element): array {
'#template' => $inline_template,
'#context' => $props,
];
return $element;
}
@@ -152,6 +156,32 @@ private function generateComponentTemplate(
return $template;
}
/**
* Merge element attributes with props attributes.
*
* #attributes property is an universal property of the Render API, used by
* many Drupal mechanisms from Core and Contrib, so we need to inject the
* values in template.
*
* @param array $element
* The render element.
*/
private function mergeElementAttributesToPropAttributes(array &$element): void {
if (!isset($element['#attributes'])) {
return;
}
// If attributes value is an array, convert it to an Attribute object as
// \Drupal\Core\Template\Atribute::merge() expects an Attribute object.
$element_attributes = is_array($element['#attributes']) ? new Attribute($element['#attributes']) : $element['#attributes'];
// Merge ['#attributes'] with the ['#props']['attributes']. So that #props
// attributes take precedence.
$element['#props']['attributes'] = empty($element['#props']['attributes'])
? $element_attributes
: $element_attributes->merge($element['#props']['attributes']);
}
/**
* {@inheritdoc}
*/
Loading