Name | django-components JSON |
Version |
0.130
JSON |
| download |
home_page | None |
Summary | A way to create simple reusable template components in Django. |
upload_time | 2025-02-20 10:52:10 |
maintainer | None |
docs_url | None |
author | None |
requires_python | <4.0,>=3.8 |
license | MIT |
keywords |
django
components
css
js
html
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# <img src="https://raw.githubusercontent.com/django-components/django-components/master/logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
[](https://pypi.org/project/django-components/) [](https://pypi.org/project/django-components/) [](https://github.com/django-components/django-components/blob/master/LICENSE/) [](https://pypistats.org/packages/django-components) [](https://github.com/django-components/django-components/actions/workflows/tests.yml)
### <table><td>[Read the full documentation](https://django-components.github.io/django-components/latest/)</td></table>
<!-- TODO - Remove this banner after a month(?), so March 2025 -->
> ⚠️ Attention ⚠️ - We migrated from `EmilStenstrom/django-components` to `django-components/django-components`.
>
> **Repo name and documentation URL changed. Package name remains the same.**
>
> Report any broken links links in [#922](https://github.com/django-components/django-components/issues/922).
`django-components` combines Django's templating system with the modularity seen
in modern frontend frameworks like Vue or React.
With `django-components` you can support Django projects small and large without leaving the Django ecosystem.
## Quickstart
A component in django-components can be as simple as a Django template and Python code to declare the component:
```django
{# components/calendar/calendar.html #}
<div class="calendar">
Today's date is <span>{{ date }}</span>
</div>
```
```py
# components/calendar/calendar.html
from django_components import Component
class Calendar(Component):
template_file = "calendar.html"
```
Or a combination of Django template, Python, CSS, and Javascript:
```django
{# components/calendar/calendar.html #}
<div class="calendar">
Today's date is <span>{{ date }}</span>
</div>
```
```css
/* components/calendar/calendar.css */
.calendar {
width: 200px;
background: pink;
}
```
```js
/* components/calendar/calendar.js */
document.querySelector(".calendar").onclick = () => {
alert("Clicked calendar!");
};
```
```py
# components/calendar/calendar.py
from django_components import Component
class Calendar(Component):
template_file = "calendar.html"
js_file = "calendar.js"
css_file = "calendar.css"
def get_context_data(self, date):
return {"date": date}
```
Use the component like this:
```django
{% component "calendar" date="2024-11-06" %}{% endcomponent %}
```
And this is what gets rendered:
```html
<div class="calendar-component">
Today's date is <span>2024-11-06</span>
</div>
```
## Features
### Modern and modular UI
- Create self-contained, reusable UI elements.
- Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.
- HTML, CSS, and JS can be defined on the component class, or loaded from files.
```python
from django_components import Component
@register("calendar")
class Calendar(Component):
template = """
<div class="calendar">
Today's date is
<span>{{ date }}</span>
</div>
"""
css = """
.calendar {
width: 200px;
background: pink;
}
"""
js = """
document.querySelector(".calendar")
.addEventListener("click", () => {
alert("Clicked calendar!");
});
"""
# Additional JS and CSS
class Media:
js = ["https://cdn.jsdelivr.net/npm/htmx.org@2.1.1/dist/htmx.min.js"]
css = ["bootstrap/dist/css/bootstrap.min.css"]
# Variables available in the template
def get_context_data(self, date):
return {
"date": date
}
```
### Composition with slots
- Render components inside templates with `{% component %}` tag.
- Compose them with `{% slot %}` and `{% fill %}` tags.
- Vue-like slot system, including scoped slots.
```django
{% component "Layout"
bookmarks=bookmarks
breadcrumbs=breadcrumbs
%}
{% fill "header" %}
<div class="flex justify-between gap-x-12">
<div class="prose">
<h3>{{ project.name }}</h3>
</div>
<div class="font-semibold text-gray-500">
{{ project.start_date }} - {{ project.end_date }}
</div>
</div>
{% endfill %}
{# Access data passed to `{% slot %}` with `data` #}
{% fill "tabs" data="tabs_data" %}
{% component "TabItem" header="Project Info" %}
{% component "ProjectInfo"
project=project
project_tags=project_tags
attrs:class="py-5"
attrs:width=tabs_data.width
/ %}
{% endcomponent %}
{% endfill %}
{% endcomponent %}
```
### Extended template tags
`django-components` extends Django's template tags syntax with:
- Literal lists and dictionaries in template tags
- Self-closing tags `{% mytag / %}`
- Multi-line template tags
- Spread operator `...` to dynamically pass args or kwargs into the template tag
- Nested template tags like `"{{ first_name }} {{ last_name }}"`
- Flat definition of dictionary keys `attr:key=val`
```django
{% component "table"
...default_attrs
title="Friend list for {{ user.name }}"
headers=["Name", "Age", "Email"]
data=[
{
"name": "John"|upper,
"age": 30|add:1,
"email": "john@example.com",
"hobbies": ["reading"],
},
{
"name": "Jane"|upper,
"age": 25|add:1,
"email": "jane@example.com",
"hobbies": ["reading", "coding"],
},
],
attrs:class="py-4 ma-2 border-2 border-gray-300 rounded-md"
/ %}
```
### HTML fragment support
`django-components` makes intergration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:
- Components's JS and CSS is loaded automatically when the fragment is inserted into the DOM.
- Expose components as views with `get`, `post`, `put`, `patch`, `delete` methods
```py
# components/calendar/calendar.py
@register("calendar")
class Calendar(Component):
template_file = "calendar.html"
def get(self, request, *args, **kwargs):
page = request.GET.get("page", 1)
return self.render_to_response(
kwargs={
"page": page,
}
)
def get_context_data(self, page):
return {
"page": page,
}
# urls.py
path("calendar/", Calendar.as_view()),
```
### Type hints
Opt-in to type hints by defining types for component's args, kwargs, slots, and more:
```py
from typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc
ButtonArgs = Tuple[int, str]
class ButtonKwargs(TypedDict):
variable: str
another: int
maybe_var: NotRequired[int] # May be omitted
class ButtonData(TypedDict):
variable: str
class ButtonSlots(TypedDict):
my_slot: NotRequired[SlotFunc]
another_slot: SlotContent
ButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots, ButtonData, JsData, CssData]
class Button(ButtonType):
def get_context_data(self, *args, **kwargs):
self.input.args[0] # int
self.input.kwargs["variable"] # str
self.input.slots["my_slot"] # SlotFunc[MySlotData]
return {} # Error: Key "variable" is missing
```
When you then call `Button.render()` or `Button.render_to_response()`, you will get type hints:
```py
Button.render(
# Error: First arg must be `int`, got `float`
args=(1.25, "abc"),
# Error: Key "another" is missing
kwargs={
"variable": "text",
},
)
```
### Debugging features
- **Visual component inspection**: Highlight components and slots directly in your browser.
- **Detailed tracing logs to supply AI-agents with context**: The logs include component and slot names and IDs, and their position in the tree.
<div style="text-align: center;">
<img src="https://github.com/django-components/django-components/blob/master/docs/images/debug-highlight-slots.png?raw=true" alt="Component debugging visualization showing slot highlighting" width="500" style="margin: auto;">
</div>
### Sharing components
- Install and use third-party components from PyPI
- Or publish your own "component registry"
- Highly customizable - Choose how the components are called in the template, and more:
```django
{% component "calendar" date="2024-11-06" %}
{% endcomponent %}
{% calendar date="2024-11-06" %}
{% endcalendar %}
```
### Other features
- Vue-like provide / inject system
- Format HTML attributes with `{% html_attrs %}`
## Documentation
[Read the full documentation here](https://django-components.github.io/django-components/latest/).
... or jump right into the code, [check out the example project](https://github.com/django-components/django-components/tree/master/sampleproject).
## Release notes
Read the [Release Notes](https://github.com/django-components/django-components/tree/master/CHANGELOG.md)
to see the latest features and fixes.
## Community examples
One of our goals with `django-components` is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.
- [django-htmx-components](https://github.com/iwanalabs/django-htmx-components): A set of components for use with [htmx](https://htmx.org/). Try out the [live demo](https://dhc.iwanalabs.com/).
- [djc-heroicons](https://pypi.org/project/djc-heroicons/): A component that renders icons from [Heroicons.com](https://heroicons.com/).
## Contributing and development
Get involved or sponsor this project - [See here](https://django-components.github.io/django-components/dev/overview/contributing/)
Running django-components locally for development - [See here](https://django-components.github.io/django-components/dev/overview/development/)
Raw data
{
"_id": null,
"home_page": null,
"name": "django-components",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.8",
"maintainer_email": null,
"keywords": "django, components, css, js, html",
"author": null,
"author_email": "Emil Stenstr\u00f6m <emil@emilstenstrom.se>",
"download_url": "https://files.pythonhosted.org/packages/41/4f/31ec6be24bbdffbcd2e8b1fe488a70f540fd95056a9e98d8a295faab06ec/django_components-0.130.tar.gz",
"platform": null,
"description": "# <img src=\"https://raw.githubusercontent.com/django-components/django-components/master/logo/logo-black-on-white.svg\" alt=\"django-components\" style=\"max-width: 100%; background: white; color: black;\">\n\n[](https://pypi.org/project/django-components/) [](https://pypi.org/project/django-components/) [](https://github.com/django-components/django-components/blob/master/LICENSE/) [](https://pypistats.org/packages/django-components) [](https://github.com/django-components/django-components/actions/workflows/tests.yml)\n\n### <table><td>[Read the full documentation](https://django-components.github.io/django-components/latest/)</td></table>\n\n<!-- TODO - Remove this banner after a month(?), so March 2025 -->\n> \u26a0\ufe0f Attention \u26a0\ufe0f - We migrated from `EmilStenstrom/django-components` to `django-components/django-components`.\n>\n> **Repo name and documentation URL changed. Package name remains the same.**\n>\n> Report any broken links links in [#922](https://github.com/django-components/django-components/issues/922).\n\n`django-components` combines Django's templating system with the modularity seen\nin modern frontend frameworks like Vue or React.\n\nWith `django-components` you can support Django projects small and large without leaving the Django ecosystem.\n\n## Quickstart\n\nA component in django-components can be as simple as a Django template and Python code to declare the component:\n\n```django\n{# components/calendar/calendar.html #}\n<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n```\n\n```py\n# components/calendar/calendar.html\nfrom django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n```\n\nOr a combination of Django template, Python, CSS, and Javascript:\n\n```django\n{# components/calendar/calendar.html #}\n<div class=\"calendar\">\n Today's date is <span>{{ date }}</span>\n</div>\n```\n\n```css\n/* components/calendar/calendar.css */\n.calendar {\n width: 200px;\n background: pink;\n}\n```\n\n```js\n/* components/calendar/calendar.js */\ndocument.querySelector(\".calendar\").onclick = () => {\n alert(\"Clicked calendar!\");\n};\n```\n\n```py\n# components/calendar/calendar.py\nfrom django_components import Component\n\nclass Calendar(Component):\n template_file = \"calendar.html\"\n js_file = \"calendar.js\"\n css_file = \"calendar.css\"\n\n def get_context_data(self, date):\n return {\"date\": date}\n```\n\nUse the component like this:\n\n```django\n{% component \"calendar\" date=\"2024-11-06\" %}{% endcomponent %}\n```\n\nAnd this is what gets rendered:\n\n```html\n<div class=\"calendar-component\">\n Today's date is <span>2024-11-06</span>\n</div>\n```\n\n## Features\n\n### Modern and modular UI\n\n- Create self-contained, reusable UI elements.\n- Each component can include its own HTML, CSS, and JS, or additional third-party JS and CSS.\n- HTML, CSS, and JS can be defined on the component class, or loaded from files.\n\n```python\nfrom django_components import Component\n\n@register(\"calendar\")\nclass Calendar(Component):\n template = \"\"\"\n <div class=\"calendar\">\n Today's date is\n <span>{{ date }}</span>\n </div>\n \"\"\"\n\n css = \"\"\"\n .calendar {\n width: 200px;\n background: pink;\n }\n \"\"\"\n\n js = \"\"\"\n document.querySelector(\".calendar\")\n .addEventListener(\"click\", () => {\n alert(\"Clicked calendar!\");\n });\n \"\"\"\n\n # Additional JS and CSS\n class Media:\n js = [\"https://cdn.jsdelivr.net/npm/htmx.org@2.1.1/dist/htmx.min.js\"]\n css = [\"bootstrap/dist/css/bootstrap.min.css\"]\n\n # Variables available in the template\n def get_context_data(self, date):\n return {\n \"date\": date\n }\n```\n\n### Composition with slots\n\n- Render components inside templates with `{% component %}` tag.\n- Compose them with `{% slot %}` and `{% fill %}` tags.\n- Vue-like slot system, including scoped slots.\n\n```django\n{% component \"Layout\"\n bookmarks=bookmarks\n breadcrumbs=breadcrumbs\n%}\n {% fill \"header\" %}\n <div class=\"flex justify-between gap-x-12\">\n <div class=\"prose\">\n <h3>{{ project.name }}</h3>\n </div>\n <div class=\"font-semibold text-gray-500\">\n {{ project.start_date }} - {{ project.end_date }}\n </div>\n </div>\n {% endfill %}\n\n {# Access data passed to `{% slot %}` with `data` #}\n {% fill \"tabs\" data=\"tabs_data\" %}\n {% component \"TabItem\" header=\"Project Info\" %}\n {% component \"ProjectInfo\"\n project=project\n project_tags=project_tags\n attrs:class=\"py-5\"\n attrs:width=tabs_data.width\n / %}\n {% endcomponent %}\n {% endfill %}\n{% endcomponent %}\n```\n\n### Extended template tags\n\n`django-components` extends Django's template tags syntax with:\n\n- Literal lists and dictionaries in template tags\n- Self-closing tags `{% mytag / %}`\n- Multi-line template tags\n- Spread operator `...` to dynamically pass args or kwargs into the template tag\n- Nested template tags like `\"{{ first_name }} {{ last_name }}\"`\n- Flat definition of dictionary keys `attr:key=val`\n\n```django\n{% component \"table\"\n ...default_attrs\n title=\"Friend list for {{ user.name }}\"\n headers=[\"Name\", \"Age\", \"Email\"]\n data=[\n {\n \"name\": \"John\"|upper,\n \"age\": 30|add:1,\n \"email\": \"john@example.com\",\n \"hobbies\": [\"reading\"],\n },\n {\n \"name\": \"Jane\"|upper,\n \"age\": 25|add:1,\n \"email\": \"jane@example.com\",\n \"hobbies\": [\"reading\", \"coding\"],\n },\n ],\n attrs:class=\"py-4 ma-2 border-2 border-gray-300 rounded-md\"\n/ %}\n```\n\n### HTML fragment support\n\n`django-components` makes intergration with HTMX, AlpineJS or jQuery easy by allowing components to be rendered as HTML fragments:\n\n- Components's JS and CSS is loaded automatically when the fragment is inserted into the DOM.\n\n- Expose components as views with `get`, `post`, `put`, `patch`, `delete` methods\n\n```py\n# components/calendar/calendar.py\n@register(\"calendar\")\nclass Calendar(Component):\n template_file = \"calendar.html\"\n\n def get(self, request, *args, **kwargs):\n page = request.GET.get(\"page\", 1)\n return self.render_to_response(\n kwargs={\n \"page\": page,\n }\n )\n\n def get_context_data(self, page):\n return {\n \"page\": page,\n }\n\n# urls.py\npath(\"calendar/\", Calendar.as_view()),\n```\n\n### Type hints\n\nOpt-in to type hints by defining types for component's args, kwargs, slots, and more:\n\n```py\nfrom typing import NotRequired, Tuple, TypedDict, SlotContent, SlotFunc\n\nButtonArgs = Tuple[int, str]\n\nclass ButtonKwargs(TypedDict):\n variable: str\n another: int\n maybe_var: NotRequired[int] # May be omitted\n\nclass ButtonData(TypedDict):\n variable: str\n\nclass ButtonSlots(TypedDict):\n my_slot: NotRequired[SlotFunc]\n another_slot: SlotContent\n\nButtonType = Component[ButtonArgs, ButtonKwargs, ButtonSlots, ButtonData, JsData, CssData]\n\nclass Button(ButtonType):\n def get_context_data(self, *args, **kwargs):\n self.input.args[0] # int\n self.input.kwargs[\"variable\"] # str\n self.input.slots[\"my_slot\"] # SlotFunc[MySlotData]\n\n return {} # Error: Key \"variable\" is missing\n```\n\nWhen you then call `Button.render()` or `Button.render_to_response()`, you will get type hints:\n\n```py\nButton.render(\n # Error: First arg must be `int`, got `float`\n args=(1.25, \"abc\"),\n # Error: Key \"another\" is missing\n kwargs={\n \"variable\": \"text\",\n },\n)\n```\n\n### Debugging features\n\n- **Visual component inspection**: Highlight components and slots directly in your browser.\n- **Detailed tracing logs to supply AI-agents with context**: The logs include component and slot names and IDs, and their position in the tree.\n\n<div style=\"text-align: center;\">\n<img src=\"https://github.com/django-components/django-components/blob/master/docs/images/debug-highlight-slots.png?raw=true\" alt=\"Component debugging visualization showing slot highlighting\" width=\"500\" style=\"margin: auto;\">\n</div>\n\n### Sharing components\n\n- Install and use third-party components from PyPI\n- Or publish your own \"component registry\"\n- Highly customizable - Choose how the components are called in the template, and more:\n\n ```django\n {% component \"calendar\" date=\"2024-11-06\" %}\n {% endcomponent %}\n\n {% calendar date=\"2024-11-06\" %}\n {% endcalendar %}\n ```\n\n### Other features\n\n- Vue-like provide / inject system\n- Format HTML attributes with `{% html_attrs %}`\n\n## Documentation\n\n[Read the full documentation here](https://django-components.github.io/django-components/latest/).\n\n... or jump right into the code, [check out the example project](https://github.com/django-components/django-components/tree/master/sampleproject).\n\n## Release notes\n\nRead the [Release Notes](https://github.com/django-components/django-components/tree/master/CHANGELOG.md)\nto see the latest features and fixes.\n\n## Community examples\n\nOne of our goals with `django-components` is to make it easy to share components between projects. If you have a set of components that you think would be useful to others, please open a pull request to add them to the list below.\n\n- [django-htmx-components](https://github.com/iwanalabs/django-htmx-components): A set of components for use with [htmx](https://htmx.org/). Try out the [live demo](https://dhc.iwanalabs.com/).\n\n- [djc-heroicons](https://pypi.org/project/djc-heroicons/): A component that renders icons from [Heroicons.com](https://heroicons.com/).\n\n## Contributing and development\n\nGet involved or sponsor this project - [See here](https://django-components.github.io/django-components/dev/overview/contributing/)\n\nRunning django-components locally for development - [See here](https://django-components.github.io/django-components/dev/overview/development/)\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A way to create simple reusable template components in Django.",
"version": "0.130",
"project_urls": {
"Changelog": "https://django-components.github.io/django-components/latest/release_notes/",
"Documentation": "https://django-components.github.io/django-components/",
"Donate": "https://github.com/sponsors/EmilStenstrom",
"Homepage": "https://github.com/django-components/django-components/",
"Issues": "https://github.com/django-components/django-components/issues"
},
"split_keywords": [
"django",
" components",
" css",
" js",
" html"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "f2c381c719f8521c98a01b3abe6188f2f0af86069a14eefc2a0df044eea91f13",
"md5": "729ce73ff7c02a9b8e65e78e37774a8e",
"sha256": "37a84d31548c70c96a5dbc0d41eddf771567e1bc46183e8b000c02cd87ae79fc"
},
"downloads": -1,
"filename": "django_components-0.130-py3-none-any.whl",
"has_sig": false,
"md5_digest": "729ce73ff7c02a9b8e65e78e37774a8e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.8",
"size": 145377,
"upload_time": "2025-02-20T10:52:09",
"upload_time_iso_8601": "2025-02-20T10:52:09.152255Z",
"url": "https://files.pythonhosted.org/packages/f2/c3/81c719f8521c98a01b3abe6188f2f0af86069a14eefc2a0df044eea91f13/django_components-0.130-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "414f31ec6be24bbdffbcd2e8b1fe488a70f540fd95056a9e98d8a295faab06ec",
"md5": "96a5507be106266b21c151d809d3b1b2",
"sha256": "8db7f74f5ff26cdecdc5fe93270cbf4bbe36022eaec5c230feed0a6c6a3ebc9c"
},
"downloads": -1,
"filename": "django_components-0.130.tar.gz",
"has_sig": false,
"md5_digest": "96a5507be106266b21c151d809d3b1b2",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.8",
"size": 130892,
"upload_time": "2025-02-20T10:52:10",
"upload_time_iso_8601": "2025-02-20T10:52:10.939687Z",
"url": "https://files.pythonhosted.org/packages/41/4f/31ec6be24bbdffbcd2e8b1fe488a70f540fd95056a9e98d8a295faab06ec/django_components-0.130.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-20 10:52:10",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "sponsors",
"github_project": "EmilStenstrom",
"github_not_found": true,
"lcname": "django-components"
}