Skip to content

[TwigComponent] Add support for namespaced templates in TemplateMap #1070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/LiveComponent/tests/Fixtures/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use Symfony\UX\LiveComponent\Tests\Fixtures\Serializer\MoneyNormalizer;
use Symfony\UX\TwigComponent\TwigComponentBundle;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Zenstruck\Foundry\ZenstruckFoundryBundle;

use function Symfony\Component\DependencyInjection\Loader\Configurator\service;
Expand All @@ -52,6 +53,13 @@ public function renderTemplate(string $template, Environment $twig = null): Resp
return new Response($twig->render("{$template}.html.twig"));
}

public function renderNamespacedTemplate(string $template, Environment $twig = null): Response
{
$twig ??= $this->container->get('twig');

return new Response($twig->render('@'.FilesystemLoader::MAIN_NAMESPACE.'/'.$template.'.html.twig'));
}

public function registerBundles(): iterable
{
yield new FrameworkBundle();
Expand Down Expand Up @@ -142,6 +150,7 @@ protected function configureRoutes(RoutingConfigurator $routes): void
->prefix('/_components');

$routes->add('template', '/render-template/{template}')->controller('kernel::renderTemplate');
$routes->add('render_namespaced_template', '/render-namespaced-template/{template}')->controller('kernel::renderNamespacedTemplate');
$routes->add('homepage', '/')->controller('kernel::index');
$routes->add('alternate_live_route', '/alt/{_live_component}/{_live_action}')->defaults(['_live_action' => 'get']);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,19 @@ public function testItAddsEmbeddedTemplateContextToEmbeddedComponents(): void
;
}

public function testItWorksWithNamespacedTemplateNamesForEmbeddedComponents(): void
{
$templateName = 'render_embedded_with_blocks.html.twig';
$obscuredName = 'fb7992f74bbb43c08e47b7cf5c880edb';
$this->addTemplateMap($obscuredName, $templateName);

$this->browser()
->visit('/render-namespaced-template/render_embedded_with_blocks')
->assertSuccessful()
->assertElementAttributeContains('.component2', 'data-live-props-value', '"data-host-template":"'.$obscuredName.'"')
;
}

public function testItUseBlocksFromEmbeddedContextUsingMultipleComponents(): void
{
$templateName = 'render_multiple_embedded_with_blocks.html.twig';
Expand Down
18 changes: 17 additions & 1 deletion src/TwigComponent/src/Twig/ComponentNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function compile(Compiler $compiler): void
->raw('), ')
->raw($this->getAttribute('only') ? '[]' : '$context')
->raw(', ')
->string($this->getAttribute('name'))
->string($this->parseTemplateName($this->getAttribute('name')))
->raw(', ')
->raw($this->getAttribute('index'))
->raw(");\n")
Expand All @@ -91,4 +91,20 @@ public function compile(Compiler $compiler): void
->raw("\n")
;
}

/**
* Copied from Twig\Loader\FilesystemLoader, and adjusted to needs for this class.
*/
private function parseTemplateName(string $name): mixed
{
if (isset($name[0]) && '@' == $name[0]) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (isset($name[0]) && '@' == $name[0]) {
if ('@' === $name[0] ?? '') {

but also test is missing to prove the fix is working.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea - a test would be ideal

Copy link
Contributor Author

@sneakyvv sneakyvv Aug 24, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test added, and branch rebased which now incorporates @weaverryan's latest test fixes. All green now here as well!

@stloyd I corrected the loose comparison. The (copied) code from Twig also used loose comparison. I guess because in this case loose comparison would be faster and if the type didn't match it would also fail (i.e. nothing would equal '@' anyway) and the type is already guaranteed because of the parameter type hint. For the same reason I kept the isset instead of ?? because it only needs one check to know to fail while the ?? would always do the assignment and then do the comparison always.

if (false === $pos = strpos($name, '/')) {
throw new \LogicException(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name));
}

return substr($name, $pos + 1);
}

return $name;
}
}