function ComponentElement::generateComponentTemplate

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

Generates the template to render the component.

Parameters

string $id: The component id.

array $slots: The contents of any potential embed blocks.

array $slots_alter_callbacks: The potential callables for altering slots.

array $context: Inline template context.

Return value

string The template.

Throws

\Drupal\Core\Render\Component\Exception\InvalidComponentDataException When slots are not render arrays.

1 call to ComponentElement::generateComponentTemplate()
ComponentElement::preRenderComponent in core/lib/Drupal/Core/Render/Element/ComponentElement.php
Expands a component into an inline template with an attachment.

File

core/lib/Drupal/Core/Render/Element/ComponentElement.php, line 97

Class

ComponentElement
Provides a Single-Directory Component render element.

Namespace

Drupal\Core\Render\Element

Code

private function generateComponentTemplate(string $id, array $slots, array $slots_alter_callbacks, array &$context) : string {
    $template = '{# This template was dynamically generated by single-directory components #}' . 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 (!Element::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;
}

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