Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/wrabit/django-cotton
Enabling Modern UI Composition in Django
https://github.com/wrabit/django-cotton
components django python ui
Last synced: about 19 hours ago
JSON representation
Enabling Modern UI Composition in Django
- Host: GitHub
- URL: https://github.com/wrabit/django-cotton
- Owner: wrabit
- License: mit
- Created: 2024-06-08T13:30:49.000Z (5 months ago)
- Default Branch: main
- Last Pushed: 2024-11-03T12:11:08.000Z (6 days ago)
- Last Synced: 2024-11-03T12:26:10.465Z (6 days ago)
- Topics: components, django, python, ui
- Language: Python
- Homepage: https://django-cotton.com
- Size: 2.51 MB
- Stars: 517
- Watchers: 10
- Forks: 21
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
- awesome-python-htmx - django-cotton - Django-a9bbcc?style=flat&logo=django&logoColor=black" alt="Django"></a> <a href="https://tailwindcss.com/" target="_blank"><img src="https://img.shields.io/badge/-Tailwind_CSS-a9bbcc?style=flat&logo=tailwindcss&logoColor=black" alt="Tailwind CSS"></a><br/> (Third Party Packages π¦ <a name = "tools"></a> / Templates)
README
# Django Cotton
![PyPI](https://img.shields.io/pypi/v/django-cotton?color=blue&style=flat-square)
![PyPI - Downloads](https://img.shields.io/pypi/dm/django-cotton?color=blue&style=flat-square)Bringing component-based design to Django templates.
- Docs site + demos: django-cotton.com
## Contents
[Why?](#why-cotton)
[Install](#install)
[Usage Basics](#usage-basics)
[Your First component](#your-first-component)
[Attributes](#add-attributes)
[Named Slots](#named-slots)
[Pass Template Variables](#pass-template-variable-as-an-attribute)
[Template expressions in attributes](#template-expressions-inside-attributes)
[Boolean attributes](#boolean-attributes)
[Passing Python data types](#passing-python-data-types)
[Increase Re-usability with `{{ attrs }}`](#increase-re-usability-with--attrs-)
[In-component Variables with ``](#in-component-variables-with-c-vars)
[HTMX Example](#an-example-with-htmx)
[Limitations in Django that Cotton overcomes](#limitations-in-django-that-cotton-overcomes)
[Configuration](#configuration)
[Caching](#caching)
[Version support](#version-support)
[Changelog](#changelog)
[Comparison with other packages](#comparison-with-other-packages)
## Why Cotton?
Cotton aims to overcome [certain limitations](#limitations-in-django-that-cotton-overcomes) that exist in the django template system that hold us back when we want to apply modern practices to compose UIs in a modular and reusable way.
## Key Features
- **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.
## Install
```bash
pip install django-cotton
```### settings.py
```python
INSTALLED_APPS = [
'django_cotton'
]
```If you have previously specified a custom loader, you should perform [manual setup](https://django-cotton.com/docs/quickstart#install).
## Usage Basics
- **Component Placement:** Components should be placed in the `templates/cotton` folder (or define a [custom folder](https://django-cotton.com/docs/configuration)).
- **Naming Conventions:**
- Component filenames use snake_case: `my_component.html`
- Components are called using kebab-case prefixed by 'c-': ``
## Walkthrough
### Your first component
```html
{{ slot }}
```
```htmlContact
```
```htmlContact
```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.
### Adding attributes
```html
{{ slot }}
```
```htmlContact
```
```html
Contact
```### Named slots
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:
```html
{{ slot }}
{% if icon %}
{{ icon }}
{% endif %}
```
```htmlContact
...
```
Named slots can also contain any django native template logic:
```html
{% if mode == 'edit' %}
...
{% else %}
...
{% endif %}
```
### Pass template variable as an attribute
To pass a template variable you prepend the attribute name with a colon `:`. Consider a bio card component:
```html
```
That has a component definition like:
```html
{{ user.username }} {{ user.country_code }}
```### Template expressions inside attributes
You can use template expression statements inside attributes.
```html
```
### Boolean attributes
Boolean attributes reduce boilerplate when we just want to indicate a certain attribute should be `True` or not.
```html
Contact
```
By passing just the attribute name without a value, it will automatically be provided to the component as `True````html
{{ slot }}
```### Passing Python data types
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
- DictionariesThis 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:
```html
{% for option in options %}
{{ option }}
{% endfor %}```
```html
```
```html
yes
no
maybe```
### Increase Re-usability with `{{ attrs }}`
`{{ 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:
```html
```
```html
```
```html
```
### In-component Variables with ``
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:
#### Using `` for default attributes
In this example we have a button component with a default "theme" but it can be overridden.
```html
{{ slot }}
```
```htmlI'm a purple button
```
```htmlNow we have a default theme for our button, but it is overridable:
```html
But I'm green
```
```html
But I'm green
```#### Using `` to govern `{{ attrs }}`
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 `` 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 ``:
```html
```
```html```
Input will have all attributes provided apart from the `icon`:
```html
```
### Dynamic Components
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.
```html
{% for field in form_fields %}
{% endfor %}
```You can also provide a template expression, should the component be inside a subdirectory or have a prefix:
```html
{% for field in form_fields %}
{% endfor %}
```
### An example with HTMX
Cotton helps carve out re-usable components, here we show how to make a re-usable form, reducing code repetition and improving maintainability:
```html
{{ slot }}
Submit```
```html
```
## Limitations in Django that Cotton overcomes
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:
### `{% block %}` and `{% extends %}`
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.### What about `{% include %}` ?
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.### What's with `{% with %}`?
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.### Custom `{% templatetags %}`
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.## Native Django template tags vs Cotton
In addition, Cotton enables you to navigate around some of the limitations with Django's native tags and template language:
### HTML in attributes
β **Django native:**
```html
{% my_component header="Header
" %}
```
β **Cotton:**
```html
Header
```
### Template expressions in attributes
β **Django native:**
```html
{% my_component model="todos.{{ index }}.name" extra="{% get_extra %}" %}
```
β **Cotton:**
```html(provides a List and Dict to component)
```### Multi-line definitions
β **Django native:**
```html
{% my_component
arg=1 %}
```
β **Cotton:**
```html```
### Dynamic components
β **Django native:**
```html
{% {{ templatetag_name }} arg=1 %}
```
β **Cotton:**
```html```
## Configuration
`COTTON_DIR` (default: "cotton")
The directory where your components are stored.
`COTTON_SNAKE_CASED_NAMES` (default: True)
Whether to search for component filenames in snake_case. If set to False, you can use kebab-cased / hyphenated filenames.
## Caching
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 warmingFor full docs and demos, checkout django-cotton.com
## Version Support
- Python >= 3.8
- Django >4.2,<5.2
## Changelog
[See releases](https://github.com/wrabit/django-cotton/releases)
## Comparison with other packages
| **Feature** | **Cotton** | **django-components** | **Slippers** |
|-----------------------------------------------------------------------------------------------------|----------------------------|----------------------------------------|------------------------------------------------------------|
| **Intro** | UI-focused, expressive syntax | Holistic solution with backend logic | Enhances DTL for reusable components |
| **Definition of βcomponentβ** | An HTML template | A backend class with template | An HTML template |
| **Syntax Style** | HTML-like | Django Template Tags | Django Template Tags with custom tags |
| **One-step package install** | β | β | β |
| **Create component in one step?** | β
(place in folder) | β
(Technically yes with single-file components) | β
(need to register in YAML file or with function) |
| **Slots**
Pass HTML content between tags | β | β | β |
| **Named Slots**
Designate a slot in the component template | β | β | β (using βfragmentsβ) |
| **Dynamic Components**
Dynamically render components based on a variable or expression | β | β | β |
| **Scoped Slots**
Reference component context in parent template | β | β | β |
| **Dynamic Attributes**
Pass string literals of basic Python types | β | β | β |
| **Boolean Attributes**
Pass valueless attributes as True | β | β | β |
| **Implicit Attribute Passing**
Pass all defined attributes to an element | β | β | β |
| **Django Template Expressions in Attribute Values**
Use template expressions in attribute values | β | β | β |
| **Attribute Merging**
Replace existing attributes with component attributes | β | β | β |
| **Multi-line Component Tags**
Write component tags over multiple lines | β | β | β |**Notes:**
- Some features here can be resolved with 3rd party plugins, for example for expressions, you can use something like `django-expr` package. So the list focus on comparison of core feature of that library.