django-components 0.64__tar.gz → 0.66__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {django_components-0.64/src/django_components.egg-info → django_components-0.66}/PKG-INFO +35 -10
- {django_components-0.64 → django_components-0.66}/README.md +34 -9
- {django_components-0.64 → django_components-0.66}/pyproject.toml +1 -1
- django_components-0.66/src/django_components/__init__.py +63 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/component.py +20 -14
- {django_components-0.64 → django_components-0.66}/src/django_components/utils.py +11 -6
- {django_components-0.64 → django_components-0.66/src/django_components.egg-info}/PKG-INFO +35 -10
- {django_components-0.64 → django_components-0.66}/tests/test_autodiscover.py +43 -1
- {django_components-0.64 → django_components-0.66}/tests/test_component.py +18 -0
- django_components-0.64/src/django_components/__init__.py +0 -40
- {django_components-0.64 → django_components-0.66}/LICENSE +0 -0
- {django_components-0.64 → django_components-0.66}/setup.cfg +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/app_settings.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/apps.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/component_registry.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/logger.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/management/__init__.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/management/commands/__init__.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/management/commands/startcomponent.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/management/commands/upgradecomponent.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/middleware.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/py.typed +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/safer_staticfiles/__init__.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/safer_staticfiles/apps.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/slots.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/template_loader.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/templatetags/__init__.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/templatetags/component_tags.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components/types.py +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components.egg-info/SOURCES.txt +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components.egg-info/dependency_links.txt +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components.egg-info/requires.txt +0 -0
- {django_components-0.64 → django_components-0.66}/src/django_components.egg-info/top_level.txt +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_component_as_view.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_context.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_dependency_rendering.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_registry.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_settings.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_startcomponent_command.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/test_templatetags.py +0 -0
- {django_components-0.64 → django_components-0.66}/tests/testutils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: django_components
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.66
|
|
4
4
|
Summary: A way to create simple reusable template components in Django.
|
|
5
5
|
Author-email: Emil Stenström <emil@emilstenstrom.se>
|
|
6
6
|
License: MIT
|
|
@@ -25,7 +25,7 @@ Description-Content-Type: text/markdown
|
|
|
25
25
|
License-File: LICENSE
|
|
26
26
|
Requires-Dist: Django>=3.2
|
|
27
27
|
|
|
28
|
-
# django-components
|
|
28
|
+
# <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
|
|
29
29
|
<a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
|
|
30
30
|
<a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
|
|
31
31
|
|
|
@@ -179,7 +179,19 @@ Django-components supports all supported combinations versions of [Django](https
|
|
|
179
179
|
|
|
180
180
|
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
|
|
181
181
|
|
|
182
|
-
|
|
182
|
+
```
|
|
183
|
+
sampleproject/
|
|
184
|
+
├── calendarapp/
|
|
185
|
+
├── components/ 🆕
|
|
186
|
+
│ └── calendar/ 🆕
|
|
187
|
+
│ ├── calendar.py 🆕
|
|
188
|
+
│ ├── script.js 🆕
|
|
189
|
+
│ ├── style.css 🆕
|
|
190
|
+
│ └── template.html 🆕
|
|
191
|
+
├── sampleproject/
|
|
192
|
+
├── manage.py
|
|
193
|
+
└── requirements.txt
|
|
194
|
+
```
|
|
183
195
|
|
|
184
196
|
Start by creating empty files in the structure above.
|
|
185
197
|
|
|
@@ -205,7 +217,7 @@ Then you need a javascript file that specifies how you interact with this compon
|
|
|
205
217
|
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
|
|
206
218
|
|
|
207
219
|
```htmldjango
|
|
208
|
-
{# In a file called [project root]/components/calendar/
|
|
220
|
+
{# In a file called [project root]/components/calendar/template.html #}
|
|
209
221
|
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
|
210
222
|
```
|
|
211
223
|
|
|
@@ -221,7 +233,7 @@ from django_components import component
|
|
|
221
233
|
class Calendar(component.Component):
|
|
222
234
|
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
|
|
223
235
|
# you can override def get_template_name() instead of specifying the below variable.
|
|
224
|
-
template_name = "calendar.html"
|
|
236
|
+
template_name = "calendar/template.html"
|
|
225
237
|
|
|
226
238
|
# This component takes one parameter, a date string to show in the template
|
|
227
239
|
def get_context_data(self, date):
|
|
@@ -230,12 +242,25 @@ class Calendar(component.Component):
|
|
|
230
242
|
}
|
|
231
243
|
|
|
232
244
|
class Media:
|
|
233
|
-
css = "style.css"
|
|
234
|
-
js = "script.js"
|
|
245
|
+
css = "calendar/style.css"
|
|
246
|
+
js = "calendar/script.js"
|
|
235
247
|
```
|
|
236
248
|
|
|
237
249
|
And voilá!! We've created our first component.
|
|
238
250
|
|
|
251
|
+
## Autodiscovery
|
|
252
|
+
|
|
253
|
+
By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
|
|
254
|
+
|
|
255
|
+
Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
|
|
256
|
+
|
|
257
|
+
If you are using autodiscovery, keep a few points in mind:
|
|
258
|
+
- Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
|
|
259
|
+
- Components inside the auto-imported files still need to be registered with `@component.register()`
|
|
260
|
+
- Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
|
|
261
|
+
|
|
262
|
+
Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
|
|
263
|
+
|
|
239
264
|
## Use the component in a template
|
|
240
265
|
|
|
241
266
|
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
|
|
@@ -262,11 +287,11 @@ The output from the above template will be:
|
|
|
262
287
|
<html>
|
|
263
288
|
<head>
|
|
264
289
|
<title>My example calendar</title>
|
|
265
|
-
<link href="style.css" type="text/css" media="all" rel="stylesheet">
|
|
290
|
+
<link href="/static/calendar/style.css" type="text/css" media="all" rel="stylesheet">
|
|
266
291
|
</head>
|
|
267
292
|
<body>
|
|
268
293
|
<div class="calendar-component">Today's date is <span>2015-06-19</span></div>
|
|
269
|
-
<script src="script.js"></script>
|
|
294
|
+
<script src="/static/calendar/script.js"></script>
|
|
270
295
|
</body>
|
|
271
296
|
<html>
|
|
272
297
|
```
|
|
@@ -331,7 +356,7 @@ In the example below we introduce two block tags that work hand in hand to make
|
|
|
331
356
|
- `{% slot <name> %}`/`{% endslot %}`: Declares a new slot in the component template.
|
|
332
357
|
- `{% fill <name> %}`/`{% endfill %}`: (Used inside a `component` tag pair.) Fills a declared slot with the specified content.
|
|
333
358
|
|
|
334
|
-
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template,
|
|
359
|
+
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template, _template.html_.
|
|
335
360
|
|
|
336
361
|
```htmldjango
|
|
337
362
|
<div class="calendar-component">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# django-components
|
|
1
|
+
# <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
|
|
2
2
|
<a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
|
|
3
3
|
<a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
|
|
4
4
|
|
|
@@ -152,7 +152,19 @@ Django-components supports all supported combinations versions of [Django](https
|
|
|
152
152
|
|
|
153
153
|
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
|
|
154
154
|
|
|
155
|
-
|
|
155
|
+
```
|
|
156
|
+
sampleproject/
|
|
157
|
+
├── calendarapp/
|
|
158
|
+
├── components/ 🆕
|
|
159
|
+
│ └── calendar/ 🆕
|
|
160
|
+
│ ├── calendar.py 🆕
|
|
161
|
+
│ ├── script.js 🆕
|
|
162
|
+
│ ├── style.css 🆕
|
|
163
|
+
│ └── template.html 🆕
|
|
164
|
+
├── sampleproject/
|
|
165
|
+
├── manage.py
|
|
166
|
+
└── requirements.txt
|
|
167
|
+
```
|
|
156
168
|
|
|
157
169
|
Start by creating empty files in the structure above.
|
|
158
170
|
|
|
@@ -178,7 +190,7 @@ Then you need a javascript file that specifies how you interact with this compon
|
|
|
178
190
|
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
|
|
179
191
|
|
|
180
192
|
```htmldjango
|
|
181
|
-
{# In a file called [project root]/components/calendar/
|
|
193
|
+
{# In a file called [project root]/components/calendar/template.html #}
|
|
182
194
|
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
|
183
195
|
```
|
|
184
196
|
|
|
@@ -194,7 +206,7 @@ from django_components import component
|
|
|
194
206
|
class Calendar(component.Component):
|
|
195
207
|
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
|
|
196
208
|
# you can override def get_template_name() instead of specifying the below variable.
|
|
197
|
-
template_name = "calendar.html"
|
|
209
|
+
template_name = "calendar/template.html"
|
|
198
210
|
|
|
199
211
|
# This component takes one parameter, a date string to show in the template
|
|
200
212
|
def get_context_data(self, date):
|
|
@@ -203,12 +215,25 @@ class Calendar(component.Component):
|
|
|
203
215
|
}
|
|
204
216
|
|
|
205
217
|
class Media:
|
|
206
|
-
css = "style.css"
|
|
207
|
-
js = "script.js"
|
|
218
|
+
css = "calendar/style.css"
|
|
219
|
+
js = "calendar/script.js"
|
|
208
220
|
```
|
|
209
221
|
|
|
210
222
|
And voilá!! We've created our first component.
|
|
211
223
|
|
|
224
|
+
## Autodiscovery
|
|
225
|
+
|
|
226
|
+
By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
|
|
227
|
+
|
|
228
|
+
Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
|
|
229
|
+
|
|
230
|
+
If you are using autodiscovery, keep a few points in mind:
|
|
231
|
+
- Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
|
|
232
|
+
- Components inside the auto-imported files still need to be registered with `@component.register()`
|
|
233
|
+
- Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
|
|
234
|
+
|
|
235
|
+
Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
|
|
236
|
+
|
|
212
237
|
## Use the component in a template
|
|
213
238
|
|
|
214
239
|
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
|
|
@@ -235,11 +260,11 @@ The output from the above template will be:
|
|
|
235
260
|
<html>
|
|
236
261
|
<head>
|
|
237
262
|
<title>My example calendar</title>
|
|
238
|
-
<link href="style.css" type="text/css" media="all" rel="stylesheet">
|
|
263
|
+
<link href="/static/calendar/style.css" type="text/css" media="all" rel="stylesheet">
|
|
239
264
|
</head>
|
|
240
265
|
<body>
|
|
241
266
|
<div class="calendar-component">Today's date is <span>2015-06-19</span></div>
|
|
242
|
-
<script src="script.js"></script>
|
|
267
|
+
<script src="/static/calendar/script.js"></script>
|
|
243
268
|
</body>
|
|
244
269
|
<html>
|
|
245
270
|
```
|
|
@@ -304,7 +329,7 @@ In the example below we introduce two block tags that work hand in hand to make
|
|
|
304
329
|
- `{% slot <name> %}`/`{% endslot %}`: Declares a new slot in the component template.
|
|
305
330
|
- `{% fill <name> %}`/`{% endfill %}`: (Used inside a `component` tag pair.) Fills a declared slot with the specified content.
|
|
306
331
|
|
|
307
|
-
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template,
|
|
332
|
+
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template, _template.html_.
|
|
308
333
|
|
|
309
334
|
```htmldjango
|
|
310
335
|
<div class="calendar-component">
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "django_components"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.66"
|
|
8
8
|
requires-python = ">=3.8, <4.0"
|
|
9
9
|
description = "A way to create simple reusable template components in Django."
|
|
10
10
|
keywords = ["django", "components", "css", "js", "html"]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import importlib.util
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import django
|
|
7
|
+
from django.conf import settings
|
|
8
|
+
from django.utils.module_loading import autodiscover_modules
|
|
9
|
+
|
|
10
|
+
from django_components.logger import logger
|
|
11
|
+
from django_components.utils import search
|
|
12
|
+
|
|
13
|
+
if django.VERSION < (3, 2):
|
|
14
|
+
default_app_config = "django_components.apps.ComponentsConfig"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def autodiscover() -> None:
|
|
18
|
+
from django_components.app_settings import app_settings
|
|
19
|
+
|
|
20
|
+
if app_settings.AUTODISCOVER:
|
|
21
|
+
# Autodetect a components.py file in each app directory
|
|
22
|
+
autodiscover_modules("components")
|
|
23
|
+
|
|
24
|
+
# Autodetect a <component>.py file in a components dir
|
|
25
|
+
component_filepaths = search(search_glob="**/*.py").matched_files
|
|
26
|
+
logger.debug(f"Autodiscover found {len(component_filepaths)} files in component directories.")
|
|
27
|
+
|
|
28
|
+
for path in component_filepaths:
|
|
29
|
+
# This imports the file and runs it's code. So if the file defines any
|
|
30
|
+
# django components, they will be registered.
|
|
31
|
+
module_name = _filepath_to_python_module(path)
|
|
32
|
+
logger.debug(f'Importing module "{module_name}" (derived from path "{path}")')
|
|
33
|
+
importlib.import_module(module_name)
|
|
34
|
+
|
|
35
|
+
for path_lib in app_settings.LIBRARIES:
|
|
36
|
+
importlib.import_module(path_lib)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _filepath_to_python_module(file_path: Path) -> str:
|
|
40
|
+
"""
|
|
41
|
+
Derive python import path from the filesystem path.
|
|
42
|
+
|
|
43
|
+
Example:
|
|
44
|
+
- If project root is `/path/to/project`
|
|
45
|
+
- And file_path is `/path/to/project/app/components/mycomp.py`
|
|
46
|
+
- Then the path relative to project root is `app/components/mycomp.py`
|
|
47
|
+
- Which we then turn into python import path `app.components.mycomp`
|
|
48
|
+
"""
|
|
49
|
+
if hasattr(settings, "BASE_DIR"):
|
|
50
|
+
project_root = str(settings.BASE_DIR)
|
|
51
|
+
else:
|
|
52
|
+
# Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634
|
|
53
|
+
project_root = os.path.abspath(os.path.dirname(__name__))
|
|
54
|
+
|
|
55
|
+
rel_path = os.path.relpath(file_path, start=project_root)
|
|
56
|
+
rel_path_without_suffix = str(Path(rel_path).with_suffix(""))
|
|
57
|
+
|
|
58
|
+
# NOTE: Path normalizes paths to use `/` as separator, while os.path
|
|
59
|
+
# uses `os.path.sep`.
|
|
60
|
+
sep = os.path.sep if os.path.sep in rel_path_without_suffix else "/"
|
|
61
|
+
module_name = rel_path_without_suffix.replace(sep, ".")
|
|
62
|
+
|
|
63
|
+
return module_name
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import inspect
|
|
2
2
|
import os
|
|
3
|
+
import sys
|
|
3
4
|
from pathlib import Path
|
|
4
5
|
from typing import Any, ClassVar, Dict, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, Union
|
|
5
6
|
|
|
@@ -73,19 +74,30 @@ def _resolve_component_relative_files(attrs: MutableMapping) -> None:
|
|
|
73
74
|
as the component class. If so, modify the attributes so the class Django's rendering
|
|
74
75
|
will pick up these files correctly.
|
|
75
76
|
"""
|
|
77
|
+
component_name = attrs["__qualname__"]
|
|
78
|
+
# Derive the full path of the file where the component was defined
|
|
76
79
|
module_name = attrs["__module__"]
|
|
80
|
+
module_obj = sys.modules[module_name]
|
|
81
|
+
file_path = module_obj.__file__
|
|
82
|
+
|
|
83
|
+
if not file_path:
|
|
84
|
+
logger.debug(
|
|
85
|
+
f"Could not resolve the path to the file for component '{component_name}'."
|
|
86
|
+
" Paths for HTML, JS or CSS templates will NOT be resolved relative to the component file."
|
|
87
|
+
)
|
|
88
|
+
return
|
|
77
89
|
|
|
78
90
|
# Prepare all possible directories we need to check when searching for
|
|
79
91
|
# component's template and media files
|
|
80
|
-
components_dirs = search()
|
|
92
|
+
components_dirs = search().searched_dirs
|
|
81
93
|
|
|
82
94
|
# Get the directory where the component class is defined
|
|
83
95
|
try:
|
|
84
|
-
comp_dir_abs, comp_dir_rel =
|
|
96
|
+
comp_dir_abs, comp_dir_rel = _get_dir_path_from_component_path(file_path, components_dirs)
|
|
85
97
|
except RuntimeError:
|
|
86
98
|
# If no dir was found, we assume that the path is NOT relative to the component dir
|
|
87
99
|
logger.debug(
|
|
88
|
-
f"No component directory found for component '{
|
|
100
|
+
f"No component directory found for component '{component_name}' in {file_path}"
|
|
89
101
|
" If this component defines HTML, JS or CSS templates relatively to the component file,"
|
|
90
102
|
" then check that the component's directory is accessible from one of the paths"
|
|
91
103
|
" specified in the Django's 'STATICFILES_DIRS' settings."
|
|
@@ -127,17 +139,11 @@ def _resolve_component_relative_files(attrs: MutableMapping) -> None:
|
|
|
127
139
|
media.js = [resolve_file(filepath) for filepath in media.js]
|
|
128
140
|
|
|
129
141
|
|
|
130
|
-
def
|
|
131
|
-
|
|
142
|
+
def _get_dir_path_from_component_path(
|
|
143
|
+
abs_component_file_path: str,
|
|
144
|
+
candidate_dirs: Union[List[str], List[Path]],
|
|
132
145
|
) -> Tuple[str, str]:
|
|
133
|
-
|
|
134
|
-
# Thus, we should get file path relative to Django project root
|
|
135
|
-
comp_path = os.sep.join(component_module_path.split("."))
|
|
136
|
-
comp_dir_path = os.path.dirname(comp_path)
|
|
137
|
-
|
|
138
|
-
# NOTE: We assume that Django project root == current working directory!
|
|
139
|
-
cwd = os.getcwd()
|
|
140
|
-
comp_dir_path_abs = os.path.join(cwd, comp_dir_path)
|
|
146
|
+
comp_dir_path_abs = os.path.dirname(abs_component_file_path)
|
|
141
147
|
|
|
142
148
|
# From all dirs defined in settings.STATICFILES_DIRS, find one that's the parent
|
|
143
149
|
# to the component file.
|
|
@@ -150,7 +156,7 @@ def _get_dir_path_from_component_module_path(
|
|
|
150
156
|
|
|
151
157
|
if root_dir_abs is None:
|
|
152
158
|
raise RuntimeError(
|
|
153
|
-
f"Failed to resolve template directory for component '{
|
|
159
|
+
f"Failed to resolve template directory for component file '{abs_component_file_path}'",
|
|
154
160
|
)
|
|
155
161
|
|
|
156
162
|
# Derive the path from matched STATICFILES_DIRS to the dir where the current component file is.
|
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
import glob
|
|
2
2
|
from pathlib import Path
|
|
3
|
-
from typing import List,
|
|
3
|
+
from typing import List, NamedTuple, Optional
|
|
4
4
|
|
|
5
5
|
from django.template.engine import Engine
|
|
6
6
|
|
|
7
7
|
from django_components.template_loader import Loader
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
class SearchResult(NamedTuple):
|
|
11
|
+
searched_dirs: List[Path]
|
|
12
|
+
matched_files: List[Path]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -> SearchResult:
|
|
11
16
|
"""
|
|
12
17
|
Search for directories that may contain components.
|
|
13
18
|
|
|
@@ -22,11 +27,11 @@ def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -
|
|
|
22
27
|
dirs = loader.get_dirs()
|
|
23
28
|
|
|
24
29
|
if search_glob is None:
|
|
25
|
-
return dirs
|
|
30
|
+
return SearchResult(searched_dirs=dirs, matched_files=[])
|
|
26
31
|
|
|
27
|
-
component_filenames: List[
|
|
32
|
+
component_filenames: List[Path] = []
|
|
28
33
|
for directory in dirs:
|
|
29
34
|
for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):
|
|
30
|
-
component_filenames.append(path)
|
|
35
|
+
component_filenames.append(Path(path))
|
|
31
36
|
|
|
32
|
-
return component_filenames
|
|
37
|
+
return SearchResult(searched_dirs=dirs, matched_files=component_filenames)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: django_components
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.66
|
|
4
4
|
Summary: A way to create simple reusable template components in Django.
|
|
5
5
|
Author-email: Emil Stenström <emil@emilstenstrom.se>
|
|
6
6
|
License: MIT
|
|
@@ -25,7 +25,7 @@ Description-Content-Type: text/markdown
|
|
|
25
25
|
License-File: LICENSE
|
|
26
26
|
Requires-Dist: Django>=3.2
|
|
27
27
|
|
|
28
|
-
# django-components
|
|
28
|
+
# <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
|
|
29
29
|
<a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
|
|
30
30
|
<a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
|
|
31
31
|
|
|
@@ -179,7 +179,19 @@ Django-components supports all supported combinations versions of [Django](https
|
|
|
179
179
|
|
|
180
180
|
A component in django-components is the combination of four things: CSS, Javascript, a Django template, and some Python code to put them all together.
|
|
181
181
|
|
|
182
|
-
|
|
182
|
+
```
|
|
183
|
+
sampleproject/
|
|
184
|
+
├── calendarapp/
|
|
185
|
+
├── components/ 🆕
|
|
186
|
+
│ └── calendar/ 🆕
|
|
187
|
+
│ ├── calendar.py 🆕
|
|
188
|
+
│ ├── script.js 🆕
|
|
189
|
+
│ ├── style.css 🆕
|
|
190
|
+
│ └── template.html 🆕
|
|
191
|
+
├── sampleproject/
|
|
192
|
+
├── manage.py
|
|
193
|
+
└── requirements.txt
|
|
194
|
+
```
|
|
183
195
|
|
|
184
196
|
Start by creating empty files in the structure above.
|
|
185
197
|
|
|
@@ -205,7 +217,7 @@ Then you need a javascript file that specifies how you interact with this compon
|
|
|
205
217
|
Now you need a Django template for your component. Feel free to define more variables like `date` in this example. When creating an instance of this component we will send in the values for these variables. The template will be rendered with whatever template backend you've specified in your Django settings file.
|
|
206
218
|
|
|
207
219
|
```htmldjango
|
|
208
|
-
{# In a file called [project root]/components/calendar/
|
|
220
|
+
{# In a file called [project root]/components/calendar/template.html #}
|
|
209
221
|
<div class="calendar-component">Today's date is <span>{{ date }}</span></div>
|
|
210
222
|
```
|
|
211
223
|
|
|
@@ -221,7 +233,7 @@ from django_components import component
|
|
|
221
233
|
class Calendar(component.Component):
|
|
222
234
|
# Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
|
|
223
235
|
# you can override def get_template_name() instead of specifying the below variable.
|
|
224
|
-
template_name = "calendar.html"
|
|
236
|
+
template_name = "calendar/template.html"
|
|
225
237
|
|
|
226
238
|
# This component takes one parameter, a date string to show in the template
|
|
227
239
|
def get_context_data(self, date):
|
|
@@ -230,12 +242,25 @@ class Calendar(component.Component):
|
|
|
230
242
|
}
|
|
231
243
|
|
|
232
244
|
class Media:
|
|
233
|
-
css = "style.css"
|
|
234
|
-
js = "script.js"
|
|
245
|
+
css = "calendar/style.css"
|
|
246
|
+
js = "calendar/script.js"
|
|
235
247
|
```
|
|
236
248
|
|
|
237
249
|
And voilá!! We've created our first component.
|
|
238
250
|
|
|
251
|
+
## Autodiscovery
|
|
252
|
+
|
|
253
|
+
By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
|
|
254
|
+
|
|
255
|
+
Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
|
|
256
|
+
|
|
257
|
+
If you are using autodiscovery, keep a few points in mind:
|
|
258
|
+
- Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
|
|
259
|
+
- Components inside the auto-imported files still need to be registered with `@component.register()`
|
|
260
|
+
- Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
|
|
261
|
+
|
|
262
|
+
Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
|
|
263
|
+
|
|
239
264
|
## Use the component in a template
|
|
240
265
|
|
|
241
266
|
First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
|
|
@@ -262,11 +287,11 @@ The output from the above template will be:
|
|
|
262
287
|
<html>
|
|
263
288
|
<head>
|
|
264
289
|
<title>My example calendar</title>
|
|
265
|
-
<link href="style.css" type="text/css" media="all" rel="stylesheet">
|
|
290
|
+
<link href="/static/calendar/style.css" type="text/css" media="all" rel="stylesheet">
|
|
266
291
|
</head>
|
|
267
292
|
<body>
|
|
268
293
|
<div class="calendar-component">Today's date is <span>2015-06-19</span></div>
|
|
269
|
-
<script src="script.js"></script>
|
|
294
|
+
<script src="/static/calendar/script.js"></script>
|
|
270
295
|
</body>
|
|
271
296
|
<html>
|
|
272
297
|
```
|
|
@@ -331,7 +356,7 @@ In the example below we introduce two block tags that work hand in hand to make
|
|
|
331
356
|
- `{% slot <name> %}`/`{% endslot %}`: Declares a new slot in the component template.
|
|
332
357
|
- `{% fill <name> %}`/`{% endfill %}`: (Used inside a `component` tag pair.) Fills a declared slot with the specified content.
|
|
333
358
|
|
|
334
|
-
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template,
|
|
359
|
+
Let's update our calendar component to support more customization. We'll add `slot` tag pairs to its template, _template.html_.
|
|
335
360
|
|
|
336
361
|
```htmldjango
|
|
337
362
|
<div class="calendar-component">
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
|
+
from unittest import mock
|
|
2
3
|
|
|
3
4
|
from django.template.engine import Engine
|
|
4
5
|
from django.urls import include, path
|
|
@@ -9,7 +10,7 @@ from .testutils import Django30CompatibleSimpleTestCase as SimpleTestCase
|
|
|
9
10
|
|
|
10
11
|
# isort: on
|
|
11
12
|
|
|
12
|
-
from django_components import autodiscover, component
|
|
13
|
+
from django_components import _filepath_to_python_module, autodiscover, component, component_registry
|
|
13
14
|
from django_components.template_loader import Loader
|
|
14
15
|
|
|
15
16
|
urlpatterns = [
|
|
@@ -25,11 +26,17 @@ class TestAutodiscover(SimpleTestCase):
|
|
|
25
26
|
del settings.SETTINGS_MODULE # noqa
|
|
26
27
|
|
|
27
28
|
def test_autodiscover_with_components_as_views(self):
|
|
29
|
+
all_components_before = component_registry.registry.all().copy()
|
|
30
|
+
|
|
28
31
|
try:
|
|
29
32
|
autodiscover()
|
|
30
33
|
except component.AlreadyRegistered:
|
|
31
34
|
self.fail("Autodiscover should not raise AlreadyRegistered exception")
|
|
32
35
|
|
|
36
|
+
all_components_after = component_registry.registry.all().copy()
|
|
37
|
+
imported_components_count = len(all_components_after) - len(all_components_before)
|
|
38
|
+
self.assertEqual(imported_components_count, 1)
|
|
39
|
+
|
|
33
40
|
|
|
34
41
|
class TestLoaderSettingsModule(SimpleTestCase):
|
|
35
42
|
def tearDown(self) -> None:
|
|
@@ -116,3 +123,38 @@ class TestBaseDir(SimpleTestCase):
|
|
|
116
123
|
Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components",
|
|
117
124
|
]
|
|
118
125
|
self.assertEqual(sorted(dirs), sorted(expected))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class TestFilepathToPythonModule(SimpleTestCase):
|
|
129
|
+
def test_prepares_path(self):
|
|
130
|
+
self.assertEqual(
|
|
131
|
+
_filepath_to_python_module(Path("tests.py")),
|
|
132
|
+
"tests",
|
|
133
|
+
)
|
|
134
|
+
self.assertEqual(
|
|
135
|
+
_filepath_to_python_module(Path("tests/components/relative_file/relative_file.py")),
|
|
136
|
+
"tests.components.relative_file.relative_file",
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def test_handles_nonlinux_paths(self):
|
|
140
|
+
with mock.patch("os.path.sep", new="//"):
|
|
141
|
+
self.assertEqual(
|
|
142
|
+
_filepath_to_python_module(Path("tests.py")),
|
|
143
|
+
"tests",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
self.assertEqual(
|
|
147
|
+
_filepath_to_python_module(Path("tests//components//relative_file//relative_file.py")),
|
|
148
|
+
"tests.components.relative_file.relative_file",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
with mock.patch("os.path.sep", new="\\"):
|
|
152
|
+
self.assertEqual(
|
|
153
|
+
_filepath_to_python_module(Path("tests.py")),
|
|
154
|
+
"tests",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
self.assertEqual(
|
|
158
|
+
_filepath_to_python_module(Path("tests\\components\\relative_file\\relative_file.py")),
|
|
159
|
+
"tests.components.relative_file.relative_file",
|
|
160
|
+
)
|
|
@@ -186,6 +186,24 @@ class ComponentTest(SimpleTestCase):
|
|
|
186
186
|
),
|
|
187
187
|
)
|
|
188
188
|
|
|
189
|
+
def test_component_with_relative_paths_as_subcomponent(
|
|
190
|
+
self,
|
|
191
|
+
):
|
|
192
|
+
template = Template(
|
|
193
|
+
"""
|
|
194
|
+
{% load component_tags %}{% component_dependencies %}
|
|
195
|
+
{% component 'parent_component' %}
|
|
196
|
+
{% fill 'content' %}
|
|
197
|
+
{% component name='relative_file_component' variable='hello' %}
|
|
198
|
+
{% endcomponent %}
|
|
199
|
+
{% endfill %}
|
|
200
|
+
{% endcomponent %}
|
|
201
|
+
""" # NOQA
|
|
202
|
+
)
|
|
203
|
+
rendered = template.render(Context({}))
|
|
204
|
+
|
|
205
|
+
self.assertIn('<input type="text" name="variable" value="hello">', rendered, rendered)
|
|
206
|
+
|
|
189
207
|
|
|
190
208
|
class InlineComponentTest(SimpleTestCase):
|
|
191
209
|
def test_inline_html_component(self):
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import importlib
|
|
2
|
-
import importlib.util
|
|
3
|
-
import sys
|
|
4
|
-
from pathlib import Path
|
|
5
|
-
from typing import Union
|
|
6
|
-
|
|
7
|
-
import django
|
|
8
|
-
from django.utils.module_loading import autodiscover_modules
|
|
9
|
-
|
|
10
|
-
from django_components.utils import search
|
|
11
|
-
|
|
12
|
-
if django.VERSION < (3, 2):
|
|
13
|
-
default_app_config = "django_components.apps.ComponentsConfig"
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def autodiscover() -> None:
|
|
17
|
-
from django_components.app_settings import app_settings
|
|
18
|
-
|
|
19
|
-
if app_settings.AUTODISCOVER:
|
|
20
|
-
# Autodetect a components.py file in each app directory
|
|
21
|
-
autodiscover_modules("components")
|
|
22
|
-
|
|
23
|
-
# Autodetect a <component>.py file in a components dir
|
|
24
|
-
component_filepaths = search(search_glob="**/*.py")
|
|
25
|
-
for path in component_filepaths:
|
|
26
|
-
import_file(path)
|
|
27
|
-
|
|
28
|
-
for path_lib in app_settings.LIBRARIES:
|
|
29
|
-
importlib.import_module(path_lib)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
def import_file(path: Union[str, Path]) -> None:
|
|
33
|
-
MODULE_PATH = path
|
|
34
|
-
MODULE_NAME = Path(path).stem
|
|
35
|
-
spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
|
|
36
|
-
if spec is None:
|
|
37
|
-
raise ValueError(f"Cannot import file '{path}' - invalid path")
|
|
38
|
-
module = importlib.util.module_from_spec(spec)
|
|
39
|
-
sys.modules[spec.name] = module
|
|
40
|
-
spec.loader.exec_module(module) # type: ignore
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components/component_registry.py
RENAMED
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components/management/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components/safer_staticfiles/apps.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components/templatetags/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components.egg-info/SOURCES.txt
RENAMED
|
File without changes
|
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components.egg-info/requires.txt
RENAMED
|
File without changes
|
{django_components-0.64 → django_components-0.66}/src/django_components.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|