Django Cotton
Django Cotton enhances Django's existing template system to enable modern UI composition through a component-based design. It introduces an HTML-like syntax for creating reusable UI components, aiming to overcome limitations in native Django templates regarding modularity and reusability. Version 2.6.2 is currently active, with a focus on seamless integration, minimal overhead through dynamic caching, and improved developer experience.
Warnings
- breaking Internal template tag names changed in version 2.4.0. While these were not officially documented for external use, direct reliance on previous internal tag names would break upon upgrade.
- gotcha If your project uses a custom `TEMPLATES` loader configuration, automatic setup by adding 'django_cotton' to `INSTALLED_APPS` might be insufficient. You may need to manually configure the `CottonLoader`.
- gotcha Components are referenced in templates using kebab-case (e.g., `<c-my-component />`), but component filenames typically use snake_case by default (e.g., `my_component.html`). This naming convention difference can sometimes be a source of confusion.
- gotcha In some setups, particularly older ones or with specific environment configurations, the HTML-like component syntax (`<c-component />`) might render as raw HTML in the browser rather than being processed by Django Cotton. The native `{% cotton %}` tag typically still works in such cases.
Install
-
pip install django-cotton
Imports
- django_cotton
INSTALLED_APPS = ['django_cotton', ...]
Quickstart
<!-- settings.py -->
INSTALLED_APPS = [
# ... other apps
'django_cotton',
]
# Optional: Manual TEMPLATES configuration if you have custom loaders
# TEMPLATES = [
# {
# 'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
# 'APP_DIRS': False, # Set to False if DIRS is used for project-level templates
# 'OPTIONS': {
# 'loaders': [
# ('django.template.loaders.cached.Loader', [
# 'django_cotton.template.loaders.CottonLoader',
# 'django.template.loaders.filesystem.Loader',
# 'django.template.loaders.app_directories.Loader',
# ]),
# ],
# 'builtins': [
# 'django_cotton.templatetags.cotton',
# ],
# },
# },
# ]
# --- In your templates directory (e.g., myproject/templates/cotton/button.html) ---
<button class="p-2 rounded-md bg-blue-500 text-white hover:bg-blue-600">
{{ slot }}
</button>
# --- In a main Django template (e.g., myproject/templates/index.html) ---
<h1 class="text-2xl font-bold">Welcome!</h1>
<c-button>Click Me</c-button>
<c-button class="bg-green-500 hover:bg-green-600">Submit</c-button>