Overview¶
django-viewcomponent is a Django library that provides a way to create reusable components for your Django project. It is inspired by ViewComponent for Ruby on Rails.
What’s a django-viewcomponent¶
django-viewcomponent is an evolution of the Django partial template, a django-viewcomponent is actually a Python object.
from django_viewcomponent import component
@component.register("hello")
class HelloComponent(component.Component):
template = "<h1>Hello, {{ self.name }}!</h1>"
def __init__(self, **kwargs):
self.title = kwargs['title']
Notes:
Here we defined a Python class
HelloComponentthat inherits fromdjango_viewcomponent.component.Component.@component.register("hello")is a decorator that registers the component with the namehello.The
templateattribute is a string that contains the HTML template for the component.The
__init__method is the constructor of the component, it receives thenameparameter and stores it in theself.nameattribute. So we can access it later in the template via{{ self.name }}.
To use the component in Django templates:
{% load viewcomponent_tags %}
{% component "hello" name='Michael Yin' %}{% endcomponent %}
The component tag will initialize the component, and pass the name parameter to the HelloComponent constructor.
The returning HTML would be:
<h1>Hello, Michael Yin!</h1>
Why use django-viewcomponent¶
Single responsibility¶
django-viewcomponent can help developers to build reusable components from the Django templates, and make the templates more readable and maintainable.
Testing¶
django-viewcomponent components are Python objects, so they can be easily tested without touching Django view and Django urls.