Skip to content
Snippets Groups Projects
Commit 9abdc69b authored by Pierre Dureau's avatar Pierre Dureau
Browse files

Merge branch '3449653-2.0.0-beta5-replace-component' into '2.0.x'

First proposal for include

See merge request !262
parents d2ca5776 9e254d2d
No related branches found
No related tags found
No related merge requests found
Pipeline #339025 failed
......@@ -5,7 +5,9 @@ declare(strict_types=1);
namespace Drupal\ui_patterns\Template;
use Drupal\ui_patterns\ComponentPluginManager;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Extension\CoreExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
......@@ -49,6 +51,7 @@ class TwigExtension extends AbstractExtension {
*/
public function getFunctions() {
return [
new TwigFunction('include', [$this, 'include'], ['needs_environment' => TRUE, 'needs_context' => TRUE, 'is_safe' => ['all']]),
new TwigFunction('component', [$this, 'renderComponent']),
new TwigFunction('_ui_patterns_preprocess_props', [$this, 'preprocessProps'], ['needs_context' => TRUE]),
];
......@@ -64,6 +67,41 @@ class TwigExtension extends AbstractExtension {
];
}
/**
* Renders a template.
*
* A hack of Twig\Extension\CoreExtension::include().
* If the template filepath is a component ID, call the renderer service
* instead of the normal include function.
* Works also for the include tag.
*/
public function include(Environment $env, $context, $template, $variables = [], $withContext = TRUE, $ignoreMissing = FALSE, $sandboxed = FALSE): array|string {
if (!preg_match('/^[a-z]([a-zA-Z0-9_-]*[a-zA-Z0-9])*:[a-z]([a-zA-Z0-9_-]*[a-zA-Z0-9])*$/', $template)) {
return CoreExtension::include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
}
if ($withContext) {
$variables = array_merge($context, $variables);
}
$component = $this->componentManager->find($template);
$definition = $component->getPluginDefinition();
$slots = [];
$props = [];
foreach ($variables as $variable => $value) {
if (isset($definition["slots"][$variable])) {
$slots[$variable] = $value;
}
elseif (isset($definition["props"]["properties"][$variable])) {
$props[$variable] = $value;
}
}
return [
"#type" => "component",
"#component" => $template,
"#slots" => $slots,
"#props" => $props,
];
}
/**
* Render given component.
*
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment