diff --git a/django_components/component.py b/django_components/component.py index 294167b0..36bbe3b9 100644 --- a/django_components/component.py +++ b/django_components/component.py @@ -97,3 +97,20 @@ def is_slot_node(node): # This variable represents the global component registry registry = ComponentRegistry() + +def register(name): + """Class decorator to register a component. + + + Usage: + + @register("my_component") + class MyComponent(component.Component): + ... + + """ + def decorator(component): + registry.register(name=name, component=component) + return component + + return decorator diff --git a/tests/test_component.py b/tests/test_component.py index 1f02f6e1..ce28a023 100644 --- a/tests/test_component.py +++ b/tests/test_component.py @@ -9,6 +9,14 @@ from .testutils import Django111CompatibleSimpleTestCase as SimpleTestCase class ComponentRegistryTest(SimpleTestCase): + + def test_register_class_decorator(self): + @component.register("decorated_component") + class TestComponent(component.Component): + pass + + self.assertEqual(component.registry.get("decorated_component"), TestComponent) + def test_empty_component(self): class EmptyComponent(component.Component): pass