![Django Cotton Logo](https://private-user-images.githubusercontent.com/5918271/346879462-1b0de6be-e943-4250-84c5-4662e2be07f5.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjUwMTc5MzksIm5iZiI6MTcyNTAxNzYzOSwicGF0aCI6Ii81OTE4MjcxLzM0Njg3OTQ2Mi0xYjBkZTZiZS1lOTQzLTQyNTAtODRjNS00NjYyZTJiZTA3ZjUucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI0MDgzMCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNDA4MzBUMTEzMzU5WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9YzA3MjVjMWE4YmQxNDRlZTExMjg2ZTczNTA1NTYzMzVkODJkYWI0YjY3NzI4OTUyNTNlZjg1OTljNjg1NGFlNyZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QmYWN0b3JfaWQ9MCZrZXlfaWQ9MCZyZXBvX2lkPTAifQ.7T56TX1o66jykykLeUcE6aCXQsoGHersRnB65nLySnk)
Bringing component-based design to Django templates.
- Docs site + demos: django-cotton.com
Why?
Install
Usage Basics
Your First component
Attributes
Named Slots
Pass Template Variables
Template expressions in attributes
Boolean attributes
Passing Python data types
Increase Re-usability with {{ attrs }}
In-component Variables with <c-vars>
HTMX Example
Limitations in Django that Cotton overcomes
Caching
Changelog
Comparison with other packages
Cotton aims to overcome certain limitations that exist in the django template system that hold us back when we want to apply modern practises to compose UIs in a modular and reusable way.
- Modern UI Composition: Efficiently compose and reuse UI components.
- Interoperable with Django: Cotton only enhances django's existing template system (no Jinja needed).
- HTML-like Syntax: Better code editor support and productivity as component tags are similar to html tags.
- Minimal Overhead: Compiles to native Django components with dynamic caching.
- Encapsulates UI: Keep layout, design and interaction in one file (especially when paired with Tailwind and Alpine.js)
- Compliments HTMX: Create smart components, reducing repetition and enhancing maintainability.
pip install django-cotton
INSTALLED_APPS = [
'django_cotton'
]
If you have previously specified a custom loader, you should perform manual setup.
- Component Placement: Components should be placed in the
templates/cotton
folder (or define a custom folder). - Naming Conventions:
- Component filenames use snake_case:
my_component.html
- Components are called using kebab-case prefixed by 'c-':
<c-my-component />
- Component filenames use snake_case:
<!-- cotton/button.html -->
<a href="/" class="...">{{ slot }}</a>
<!-- in view -->
<c-button>Contact</c-button>
<!-- html output -->
<a href="/" class="...">Contact</a>
Everything provided between the opening and closing tag is provided to the component as {{ slot }}
. It can contain any content, HTML or Django template expression.
<!-- cotton/button.html -->
<a href="{{ url }}" class="...">
{{ slot }}
</a>
<!-- in view -->
<c-button url="/contact">Contact</c-button>
<!-- html output -->
<a href="/contact" class="...">
Contact
</a>
Named slots are a powerful concept. They allow us to provide HTML to appear in one or more areas in the component. Here we allow the button to optionally display an svg icon:
<!-- cotton/button.html -->
<a href="{{ url }}" class="...">
{{ slot }}
{% if icon %}
{{ icon }}
{% endif %}
</a>
<!-- in view -->
<c-button url="/contact">
Contact
<c-slot name="icon">
<svg>...</svg>
</c-slot>
</c-button>
Named slots can also contain any django native template logic:
<!-- in view -->
<c-button url="/contact">
<c-slot name="icon">
{% if mode == 'edit' %}
<svg id="pencil">...</svg>
{% else %}
<svg id="disk">...</svg>
{% endif %}
</c-slot>
</c-button>
To pass a template variable you prepend the attribute name with a colon :
. Consider a bio card component:
<!-- in view -->
<c-bio-card :user="user" />
That has a component definition like:
<!-- cotton/bio_card.html -->
<div class="...">
<img src="{{ user.avatar }}" alt="...">
{{ user.username }} {{ user.country_code }}
</div>
You can use template expression statements inside attributes.
<c-weather icon="fa-{{ icon }}"
unit="{{ unit|default:'c' }}"
condition="very {% get_intensity %}"
/>
Boolean attributes reduce boilerplate when we just want to indicate a certain attribute should be True
or not.
<!-- in view -->
<c-button url="/contact" external>Contact</c-button>
By passing just the attribute name without a value, it will automatically be provided to the component as True
<!-- cotton/button.html -->
<a href="{{ url }}" {% if external %} target="_blank" {% endif %} class="...">
{{ slot }}
</a>
Using the ':' to prefix an attribute tells Cotton we're passing a dynamic type down. We already know we can use this to send a variable, but you can also send basic python types, namely:
- Integers and Floats
- None, True and False
- Lists
- Dictionaries
This benefits a number of use-cases, for example if you have a select component that you want to provide the possible options from the parent:
<!-- cotton/select.html -->
<select {{ attrs }}>
{% for option in options %}
<option value="{{ option }}">{{ option }}</option>
{% endfor %}
</select>
<c-select name="q1" :options="['yes', 'no', 'maybe']" />
<!-- source code output -->
<select name="q1">
<option value="yes">yes</option>
<option value="no">no</option>
<option value="maybe">maybe</option>
</select>
{{ attrs }}
is a special variable that contains all the attributes passed to the component in an key="value" format. This is useful when you want to pass all attributes to a child element without having to explicitly define them in the component template. For example, you have inputs that can have any number of attributes defined:
<!-- cotton/input.html -->
<input type="text" class="..." {{ attrs }} />
<!-- example usage -->
<c-input placeholder="Enter your name" />
<c-input name="country" id="country" value="Japan" required />
<!-- html output -->
<input type="text" class="..." placeholder="Enter your name" />
<input type="text" class="..." name="country" id="country" value="Japan" required />
Django templates adhere quite strictly to the MVC model and does not permit a lot of data manipulation in views. Fair enough, but what if we want to handle data for the purpose of UI state only? Having presentation related variables defined in the back is overkill and can quickly lead to higher maintenance cost and loses encapsulation of the component. Cotton allows you define in-component variables for the following reasons:
In this example we have a button component with a default "theme" but it can be overridden.
<!-- cotton/button.html -->
<c-vars theme="bg-purple-500" />
<a href="..." class="{{ theme }}">
{{ slot }}
</a>
<!-- in view -->
<c-button>I'm a purple button</c-button>
<!-- html output -->
<a href="..." class="bg-purple-500">
I'm a purple button
</a>
Now we have a default theme for our button, but it is overridable:
<!-- in view -->
<c-button theme="bg-green-500">But I'm green</c-button>
<!-- html output -->
<a href="..." class="bg-green-500">
But I'm green
</a>
Using {{ attrs }}
to pass all attributes from parent scope onto an element in the component, you'll sometimes want to provide additional properties to the component which are not intended to be an attributes. In this case you can declare them in <c-vars />
and it will prevent it from being in {{ attrs }}
Take this example where we want to provide any number of attributes to an input but also an icon setting which is not intened to be an attribute on <input>
:
<!-- in view -->
<c-input type="password" id="password" icon="padlock" />
<!-- cotton/input.html -->
<c-vars icon />
<img src="icons/{{ icon }}.png" />
<input {{ attrs }} />
Input will have all attributes provided apart from the icon
:
<input type="password" id="password" />
Sometimes there is a need to include a component dynamically, for example, you are looping through some data and the type of component is defined within a variable.
<!--
form_fields = [
{'type': 'text'},
{'type': 'textarea'},
{'type': 'checkbox'}
]
-->
{% for field in form_fields %}
<c-component :is="field.type" />
{% endfor %}
You can also provide a template expression, should the component be inside a subdirectory or have a prefix:
{% for field in form_fields %}
<!-- subfolder -->
<c-component is="form-fields.{{ field.type }}" />
<!-- component prefix -->
<c-component is="field_{{ field.type }}" />
{% endfor %}
Cotton helps carve out re-usable components, here we show how to make a re-usable form, reducing code repetition and improving maintainability:
<!-- cotton/form.html -->
<div id="result" class="..."></div>
<form {{ attrs }} hx-target="#result" hx-swap="outerHTML">
{{ slot }}
<button type="submit">Submit</button>
</form>
<!-- in view -->
<c-form hx-post="/contact">
<input type="text" name="name" placeholder="Name" />
<input type="text" name="email" placeholder="Email" />
<input type="checkbox" name="signup" />
</c-form>
<c-form hx-post="/buy">
<input type="text" name="type" />
<input type="text" name="quantity" />
</c-form>
Whilst you can build frontends with Django’s native tags, there are a few things that hold us back when we want to apply modern practices:
This system strongly couples child and parent templates making it hard to create a truly re-usable component that can be used in places without it having a related base template.
Modern libraries allow components to be highly configurable, whether it’s by attributes, passing variables, passing HTML with default and named slots. {% include %} tags, whilst they have the ability to pass simple variables and text, they will not allow you to easily send HTML blocks with template expressions let alone other niceties such as boolean attributes, named slots etc.
Whilst {% with %} tags allow us to provide variables and strings it quickly busies up your code and has the same limitations about passing more complex types.
Cotton does essentially compile down to templatetags but there is some extra work it performs above it to help with scoping and auto-managing keys which will be difficult to manage manually in complex nested structures.
In addition, Cotton enables you to navigate around some of the limitations with Django's native tags and template language:
❌ Django native:
{% my_component header="<h1>Header</h1>" %}
✅ Cotton:
<c-my-component>
<c-slot name="header">
<h1>Header</h1>
</c-slot>
</c-my-component>
❌ Django native:
{% my_component model="todos.{{ index }}.name" extra="{% get_extra %}" %}
✅ Cotton:
<c-my-component model="todos.{{ index }}.name" extra="{% get_extra %} />
❌ Django native:
{% my_component default_options="['yes', 'no', 'maybe']" %}
{% my_component config="{'open': True}" %}
✅ Cotton:
<c-my-component :default_options="['yes', 'no', 'maybe']" />
<c-my-component :config="{'open': True}" />
❌ Django native:
{% my_component
arg=1 %}
✅ Cotton:
<c-my-component
class="blue"
x-data="{
something: 1
}" />
Cotton is optimal when used with Django's cached.Loader. If you use automatic configuration then the cached loader will be automatically applied. This feature has room for improvement, some desirables are:
- Integration with a cache backend to survive runtime restarts / deployments.
- Cache warming
For full docs and demos, checkout django-cotton.com
Version | Date | Title and Description |
---|---|---|
v0.9.32 | 2024-08-24 | Dynamic components <c-component :is="component_name" /> , <c-component is="icon_{{ icon_name }}" /> |
v0.9.31 | 2024-08-23 | Fixed bug in auto-setup |
v0.9.30 | 2024-08-23 | Fixes an issue where by attribute order defined inside default slots were not being kept, causing template expression issues. |
v0.9.29 | 2024-08-22 | Added an auto setup script on boot that manage settings.py with fallback. Overhauled caching and adopted django's template caching with custom fallback. |
v0.9.28 | 2024-08-21 | Reverted cache changes due to cache not recognising file updates. |
v0.9.27 | 2024-08-21 | Resolved issues with component caching in dev environments. |
v0.9.26 | 2024-08-19 | We now check if a template contains any cotton syntax before processing it. |
v0.9.25 | 2024-08-12 | Fix case sensitive placeholder issue in connection with duplicate attribute handling mechanism. |
v0.9.24 | 2024-08-12 | Fixes whitespace preservation around template expressions used in attribute names. |
v0.9.23 | 2024-07-21 | Fixed an issue causing closing tags to become mutated, resolved with better whitespace handling. |
v0.9.22 | 2024-07-19 | We now scan all app directories for templates, as if APP_DIRS = True. |
v0.9.21 | 2024-07-19 | Fixed issue where '=' was breaking the attribute parsing by _component. |
v0.9.20 | 2024-07-17 | Set Charset from Engine Charset when processing template files should be utf-8 or as defined in the loader settings. |
v0.9.19 | 2024-07-14 | Fix: Cotton Loader Permits Duplicate Attributes in HTML Tags Fixed issue where the loader was not allowing Django template expressions to govern whole attributes inside HTML elements. |
v0.9.18 | 2024-07-13 | Fix: Allow Trailing/Leading Quotes in Attributes |
v0.9.17 | 2024-07-11 | Minor Cleanup |
v0.9.16 | 2024-07-10 | Cotton Component Caching Cotton components are now cached whilst in production / DEBUG = False . LRU cache type with a record count of 1024, cleared on app restart. |
v0.9.15 | 2024-07-06 | Hyphen to Underscore Conversion Converts variable names with hyphens to underscores for attribute access. i.e. <c-component x-data="{}" /> -> {{ x_data }} |
v0.9.14 | 2024-07-05 | c-vars Optimization Optimizes c-vars processing for performance, yielding a 15% speed improvement in component rendering. |
v0.9.13 | 2024-07-05 | Multi-line Attribute Support Enables multi-line values in attributes, allowing more support for js-expression style attributes like in alpine.js |
v0.9.12 | 2024-07-03 | Dropped ".cotton.html" Requirement Cotton no longer requires the .cotton.html suffix on component or view templates. A simple .html will do. |
v0.9.11 | 2024-06-24 | Attribute Ordering Fix Attribute ordering was not being kept during compilation which was breaking situations when using template expressions inside tags. |
v0.9.10 | 2024-06-22 | Template Expression Attributes Ensures that the new template expression attributes are also provided in {{ attrs }} alongside all normal attributes. |
v0.9.9 | 2024-06-22 | Native Tags in Attributes Cotton now allows you to include template variables inside attributes. Added expression attributes to {{ attrs }} . |
v0.9.7 | 2024-06-21 | Dynamic Type Attributes Using the : to prefix an attribute tells Cotton we're passing a dynamic type down. You can also send basic Python types. |
v0.9.6 | 2024-06-17 | Rename c-props to c-vars Rename c props, all <c-props /> are now <c-vars /> . |
v0.9.4 | 2024-06-11 | Boolean Attributes Support for Boolean attributes added with docs update. |
v0.9.1 | 2024-06-08 | Open Source Release Open source release. |
Note: For mistakes or if I have missed something from other packages - please create an issue!
Feature | Cotton | django-components | Slippers | Django Template Partials |
---|---|---|---|---|
Intro | UI-focused, expressive syntax | Holistic solution with backend logic | Enhances DTL for reusable components | Define and reuse inline HTML partials |
Definition of ‘component’ | An HTML template | A backend class with template | An HTML template | Inline specified partial |
Syntax Style HTML-like |
HTML-like | Django Template Tags | Django Template Tags with custom tags | Django Template Tags |
Create component in one step? | Yes (place in folder) |
No (create additional class file) |
No (need to register in YAML file or with function) |
Yes (declare inline or load via include tag) |
Slots (default) Pass HTML content between tags |
Yes | Yes | Yes | No |
Named Slots Designate a slot in the component template |
Yes | Yes | Yes, using ‘fragment’ | No |
Dynamic Components Dynamically render components based on a variable or expression |
Yes | No | No | No |
Scoped Slots Reference component context in parent template |
No | Yes | No | No |
Dynamic Attributes Pass string literals of basic Python types |
Yes | No | No | No |
Boolean Attributes Pass valueless attributes as True |
Yes | Yes | No | No |
Declare Variables in Component View Set defaults for UI states |
Yes | No (Use class properties) |
Yes | No |
Implicit Attribute Passing Pass all defined attributes to an element |
Yes | No | Yes | No |
Django Template Expressions in Attribute Values Use Django expressions in attribute values |
Yes | No | No | No |
Auto-Registering Components Start using components without manual registration |
Yes | No (Create class with decorator) |
No (Register in YAML file or with helper function) |
Yes |
Attribute Merging Replace existing attributes with component attributes |
Yes | Yes | No | No |
Multi-line Component Tags Write component tags over multiple lines |
Yes | No | No | No |