Skip to content

Commit

Permalink
[Twig] add a component name/template "namespace" notation
Browse files Browse the repository at this point in the history
  • Loading branch information
kbond committed Sep 12, 2022
1 parent 5f484d6 commit 8d43965
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function process(ContainerBuilder $container): void

$tag['service_id'] = $id;
$tag['class'] = $definition->getClass();
$tag['template'] = $tag['template'] ?? "components/{$tag['key']}.html.twig";
$tag['template'] = $tag['template'] ?? self::normalizeDefaultTemplatePath($tag['key']);
$componentConfig[$tag['key']] = $tag;
}
}
Expand All @@ -50,4 +50,9 @@ public function process(ContainerBuilder $container): void
->setArgument(2, $componentConfig)
;
}

private static function normalizeDefaultTemplatePath(string $name): string
{
return sprintf('components/%s.html.twig', str_replace(':', '/', $name));
}
}
8 changes: 8 additions & 0 deletions src/TwigComponent/src/Resources/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,14 @@ as the second argument to the ``AsTwigComponent`` attribute:
// ...
}
Twig Template Namespaces
~~~~~~~~~~~~~~~~~~~~~~~~

You can use a ``:`` in your component's name to indicate a namespace. The default
template will replace the ``:`` with ``/``. For example, a component with the
name ``form:input`` will look for a template in
``templates/components/form/input.html.twig``.

The mount() Method
~~~~~~~~~~~~~~~~~~

Expand Down
19 changes: 19 additions & 0 deletions src/TwigComponent/tests/Fixtures/Component/NamespacedComponent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\TwigComponent\Tests\Fixtures\Component;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent('foo:bar:baz')]
final class NamespacedComponent
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Content...
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ public function testCanRenderEmbeddedComponent(): void
$this->assertStringContainsString('custom td (1)', $output);
}

public function testComponentWithNamespace(): void
{
$output = $this->renderComponent('foo:bar:baz');

$this->assertStringContainsString('Content...', $output);
}

private function renderComponent(string $name, array $data = []): string
{
return self::getContainer()->get(Environment::class)->render('render_component.html.twig', [
Expand Down

0 comments on commit 8d43965

Please sign in to comment.