class ComponentElement

Same name in this branch
  1. 11.x core/lib/Drupal/Core/Render/Element/ComponentElement.php \Drupal\Core\Render\Element\ComponentElement
Same name and namespace in other branches
  1. 10 core/modules/sdc/src/Element/ComponentElement.php \Drupal\sdc\Element\ComponentElement
  2. 10 core/lib/Drupal/Core/Render/Element/ComponentElement.php \Drupal\Core\Render\Element\ComponentElement

Provides a Single Directory Component render element.

Properties:

  • #component: The machine name of the component.
  • #props: an associative array where the keys are the names of the component props, and the values are the prop values.
  • #slots: an associative array where the keys are the slot names, and the values are the slot values. Expected slot values are renderable arrays.
  • #propsAlter: an array of trusted callbacks. These are used to prepare the context. Typical uses include replacing tokens in props.
  • #slotsAlter: an array of trusted callbacks to alter the render array in #slots.

Usage Example:

$build['component'] = [
    '#type' => 'component',
    '#component' => 'olivero:button',
];

Plugin annotation

@RenderElement("component");

Hierarchy

Expanded class hierarchy of ComponentElement

See also

\Drupal\Core\Render\Element\Textarea

17 #type uses of ComponentElement
ComponentInFormTest::buildForm in core/tests/Drupal/KernelTests/Components/ComponentInFormTest.php
Form constructor.
ComponentNodeVisitorTest::testDebugRendersComponentStartWithVariant in core/tests/Drupal/KernelTests/Components/ComponentNodeVisitorTest.php
Test debug output for sdc components with component id and variant.
ComponentRenderTest::checkEmbedWithNested in core/modules/sdc/tests/src/Kernel/ComponentRenderTest.php
Render a card with slots that include a CTA component.
ComponentRenderTest::checkEmbedWithNested in core/tests/Drupal/KernelTests/Components/ComponentRenderTest.php
Render a card with slots that include a CTA component.
ComponentRenderTest::checkEmptyProps in core/tests/Drupal/KernelTests/Components/ComponentRenderTest.php
Ensure that components can have 0 props.

... See full list

File

core/modules/sdc/src/Element/ComponentElement.php, line 37

Namespace

Drupal\sdc\Element
View source
class ComponentElement extends RenderElement {
    use DoTrustedCallbackTrait;
    
    /**
     * Expands a sdc into an inline template with an attachment.
     *
     * @param array $element
     *   The element to process. See main class documentation for properties.
     *
     * @return array
     *   The form element.
     *
     * @throws \Drupal\sdc\Exception\InvalidComponentDataException
     */
    public function preRenderComponent(array $element) : array {
        $props = $element['#props'];
        $props_alter_callbacks = $element['#propsAlter'];
        // This callback can be used to prepare the context. For instance to replace
        // tokens in the props.
        $props = array_reduce($props_alter_callbacks, fn(array $carry, callable $callback) => $this->doTrustedCallback($callback, [
            $carry,
        ], '%s is not trusted'), $props);
        $inline_template = $this->generateComponentTemplate($element['#component'], $element['#slots'], $element['#slotsAlter'], $props);
        $element['inline-template'] = [
            '#type' => 'inline_template',
            '#template' => $inline_template,
            '#context' => $props,
        ];
        return $element;
    }
    
    /**
     * Generates the template to render the component.
     *
     * @param string $id
     *   The component id.
     * @param array $slots
     *   The contents of any potential embed blocks.
     * @param array $slots_alter_callbacks
     *   The potential callables for altering slots.
     * @param array $context
     *   Inline template context.
     *
     * @return string
     *   The template.
     *
     * @throws \Drupal\sdc\Exception\InvalidComponentDataException
     *   When slots are not render arrays.
     */
    private function generateComponentTemplate(string $id, array $slots, array $slots_alter_callbacks, array &$context) : string {
        $template = '{# This template was dynamically generated by sdc #}' . PHP_EOL;
        $template .= sprintf('{%% embed \'%s\' %%}', $id);
        $template .= PHP_EOL;
        foreach ($slots as $slot_name => $slot_value) {
            if (\is_scalar($slot_value)) {
                $slot_value = [
                    "#plain_text" => (string) $slot_value,
                ];
            }
            if (!Utilities::isRenderArray($slot_value)) {
                $message = sprintf('Unable to render component "%s". A render array or a scalar is expected for the slot "%s" when using the render element with the "#slots" property', $id, $slot_name);
                throw new InvalidComponentDataException($message);
            }
            $context[$slot_name] = array_reduce($slots_alter_callbacks, fn(array $carry, callable $callback) => $this->doTrustedCallback($callback, [
                $carry,
                $context,
            ], '%s is not trusted'), $slot_value);
            $template .= "  {% block {$slot_name} %}" . PHP_EOL . "    {{ {$slot_name} }}" . PHP_EOL . "  {% endblock %}" . PHP_EOL;
        }
        $template .= '{% endembed %}' . PHP_EOL;
        return $template;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getInfo() : array {
        return [
            '#pre_render' => [
                [
                    $this,
                    'preRenderComponent',
                ],
            ],
            '#component' => '',
            '#props' => [],
            '#slots' => [],
            '#propsAlter' => [],
            '#slotsAlter' => [],
        ];
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
ComponentElement::generateComponentTemplate private function Generates the template to render the component.
ComponentElement::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
ComponentElement::preRenderComponent public function Expands a sdc into an inline template with an attachment.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DoTrustedCallbackTrait::doTrustedCallback public function Performs a callback.
MessengerTrait::$messenger protected property The messenger. 25
MessengerTrait::messenger public function Gets the messenger. 25
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin ID.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin ID of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable Deprecated public function Determines if the plugin is configurable.
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript. Overrides RenderElementBase::preRenderAjaxForm
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering. Overrides RenderElementBase::preRenderGroup
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. Overrides RenderElementBase::processAjaxForm
RenderElement::processGroup public static function Arranges elements into groups. Overrides RenderElementBase::processGroup
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides RenderElementBase::setAttributes
RenderElement::__construct public function Constructs a new render element object. Overrides RenderElementBase::__construct 1
RenderElementBase::$renderParent protected property The parent element.
RenderElementBase::$renderParentName protected property The parent key.
RenderElementBase::$storage protected property The storage.
RenderElementBase::addChild public function Adds a child render element. Overrides ElementInterface::addChild
RenderElementBase::changeType public function Change the type of the element. Overrides ElementInterface::changeType
RenderElementBase::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create 2
RenderElementBase::createChild public function Creates a render object and attaches it to the current render object. Overrides ElementInterface::createChild
RenderElementBase::elementInfoManager protected function Returns the element info manager.
RenderElementBase::getChild public function Gets a child. Overrides ElementInterface::getChild
RenderElementBase::getChildren public function Returns child elements. Overrides ElementInterface::getChildren
RenderElementBase::initializeInternalStorage public function Initialize storage. Overrides ElementInterface::initializeInternalStorage
RenderElementBase::removeChild public function Removes a child. Overrides ElementInterface::removeChild
RenderElementBase::setType protected function Set type on initialize. 1
RenderElementBase::toRenderable public function Returns a render array. Overrides ElementInterface::toRenderable
RenderElementBase::__get public function Magic method: gets a property value.
RenderElementBase::__isset public function Magic method: checks if a property value is set.
RenderElementBase::__set public function Magic method: Sets a property value.
RenderElementBase::__sleep public function Overrides DependencySerializationTrait::__sleep
RenderElementBase::__unset public function Magic method: unsets a property value.
RenderElementBase::__wakeup public function Overrides DependencySerializationTrait::__wakeup
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language. 1

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.