Django Cotton

2.6.2 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

1. Add `django_cotton` to your `INSTALLED_APPS` in `settings.py`. This typically configures the necessary template loaders automatically. 2. Create a `cotton` directory within your Django app's `templates` folder or a project-level `templates` folder. 3. Define a component, for example, `button.html`, inside the `cotton` directory. The `{{ slot }}` variable renders any content passed between the component's opening and closing tags. 4. Use the component in your main Django templates using the HTML-like `c-` prefixed tag and kebab-case naming.

<!-- 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>

view raw JSON →