django-components 0.80__tar.gz → 0.82__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.
Files changed (56) hide show
  1. {django_components-0.80/src/django_components.egg-info → django_components-0.82}/PKG-INFO +350 -11
  2. {django_components-0.80 → django_components-0.82}/README.md +349 -10
  3. {django_components-0.80 → django_components-0.82}/pyproject.toml +1 -1
  4. {django_components-0.80 → django_components-0.82}/src/django_components/component.py +291 -261
  5. django_components-0.82/src/django_components/component_media.py +350 -0
  6. {django_components-0.80 → django_components-0.82}/src/django_components/component_registry.py +1 -1
  7. {django_components-0.80 → django_components-0.82}/src/django_components/slots.py +31 -16
  8. {django_components-0.80 → django_components-0.82/src/django_components.egg-info}/PKG-INFO +350 -11
  9. {django_components-0.80 → django_components-0.82}/src/django_components.egg-info/SOURCES.txt +1 -0
  10. {django_components-0.80 → django_components-0.82}/tests/test_autodiscover.py +3 -1
  11. django_components-0.82/tests/test_component.py +511 -0
  12. {django_components-0.80 → django_components-0.82}/tests/test_component_as_view.py +8 -8
  13. django_components-0.82/tests/test_component_media.py +861 -0
  14. django_components-0.80/tests/test_component.py +0 -128
  15. django_components-0.80/tests/test_component_media.py +0 -388
  16. {django_components-0.80 → django_components-0.82}/LICENSE +0 -0
  17. {django_components-0.80 → django_components-0.82}/setup.cfg +0 -0
  18. {django_components-0.80 → django_components-0.82}/src/django_components/__init__.py +0 -0
  19. {django_components-0.80 → django_components-0.82}/src/django_components/app_settings.py +0 -0
  20. {django_components-0.80 → django_components-0.82}/src/django_components/apps.py +0 -0
  21. {django_components-0.80 → django_components-0.82}/src/django_components/attributes.py +0 -0
  22. {django_components-0.80 → django_components-0.82}/src/django_components/context.py +0 -0
  23. {django_components-0.80 → django_components-0.82}/src/django_components/expression.py +0 -0
  24. {django_components-0.80 → django_components-0.82}/src/django_components/logger.py +0 -0
  25. {django_components-0.80 → django_components-0.82}/src/django_components/management/__init__.py +0 -0
  26. {django_components-0.80 → django_components-0.82}/src/django_components/management/commands/__init__.py +0 -0
  27. {django_components-0.80 → django_components-0.82}/src/django_components/management/commands/startcomponent.py +0 -0
  28. {django_components-0.80 → django_components-0.82}/src/django_components/management/commands/upgradecomponent.py +0 -0
  29. {django_components-0.80 → django_components-0.82}/src/django_components/middleware.py +0 -0
  30. {django_components-0.80 → django_components-0.82}/src/django_components/node.py +0 -0
  31. {django_components-0.80 → django_components-0.82}/src/django_components/provide.py +0 -0
  32. {django_components-0.80 → django_components-0.82}/src/django_components/py.typed +0 -0
  33. {django_components-0.80 → django_components-0.82}/src/django_components/safer_staticfiles/__init__.py +0 -0
  34. {django_components-0.80 → django_components-0.82}/src/django_components/safer_staticfiles/apps.py +0 -0
  35. {django_components-0.80 → django_components-0.82}/src/django_components/template_loader.py +0 -0
  36. {django_components-0.80 → django_components-0.82}/src/django_components/template_parser.py +0 -0
  37. {django_components-0.80 → django_components-0.82}/src/django_components/templatetags/__init__.py +0 -0
  38. {django_components-0.80 → django_components-0.82}/src/django_components/templatetags/component_tags.py +0 -0
  39. {django_components-0.80 → django_components-0.82}/src/django_components/types.py +0 -0
  40. {django_components-0.80 → django_components-0.82}/src/django_components/utils.py +0 -0
  41. {django_components-0.80 → django_components-0.82}/src/django_components.egg-info/dependency_links.txt +0 -0
  42. {django_components-0.80 → django_components-0.82}/src/django_components.egg-info/requires.txt +0 -0
  43. {django_components-0.80 → django_components-0.82}/src/django_components.egg-info/top_level.txt +0 -0
  44. {django_components-0.80 → django_components-0.82}/tests/test_attributes.py +0 -0
  45. {django_components-0.80 → django_components-0.82}/tests/test_command_startcomponent.py +0 -0
  46. {django_components-0.80 → django_components-0.82}/tests/test_context.py +0 -0
  47. {django_components-0.80 → django_components-0.82}/tests/test_dependency_rendering.py +0 -0
  48. {django_components-0.80 → django_components-0.82}/tests/test_registry.py +0 -0
  49. {django_components-0.80 → django_components-0.82}/tests/test_settings.py +0 -0
  50. {django_components-0.80 → django_components-0.82}/tests/test_template_parser.py +0 -0
  51. {django_components-0.80 → django_components-0.82}/tests/test_templatetags.py +0 -0
  52. {django_components-0.80 → django_components-0.82}/tests/test_templatetags_component.py +0 -0
  53. {django_components-0.80 → django_components-0.82}/tests/test_templatetags_provide.py +0 -0
  54. {django_components-0.80 → django_components-0.82}/tests/test_templatetags_slot_fill.py +0 -0
  55. {django_components-0.80 → django_components-0.82}/tests/test_templatetags_templating.py +0 -0
  56. {django_components-0.80 → django_components-0.82}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.80
3
+ Version: 0.82
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
@@ -59,7 +59,8 @@ Read on to learn about the details!
59
59
  - [Rendering HTML attributes](#rendering-html-attributes)
60
60
  - [Prop drilling and dependency injection (provide / inject)](#prop-drilling-and-dependency-injection-provide--inject)
61
61
  - [Component context and scope](#component-context-and-scope)
62
- - [Rendering JS and CSS dependencies](#rendering-js-and-css-dependencies)
62
+ - [Defining HTML/JS/CSS files](#defining-htmljscss-files)
63
+ - [Rendering JS/CSS dependencies](#rendering-jscss-dependencies)
63
64
  - [Available settings](#available-settings)
64
65
  - [Logging and debugging](#logging-and-debugging)
65
66
  - [Management Command](#management-command)
@@ -69,6 +70,10 @@ Read on to learn about the details!
69
70
 
70
71
  ## Release notes
71
72
 
73
+ 🚨📢 **Version 0.81** Aligned the `render_to_response` method with the (now public) `render` method of `Component` class. Moreover, slots passed to these can now be rendered also as functions.
74
+
75
+ - BREAKING CHANGE: The order of arguments to `render_to_response` has changed.
76
+
72
77
  **Version 0.80** introduces dependency injection with the `{% provide %}` tag and `inject()` method.
73
78
 
74
79
  🚨📢 **Version 0.79**
@@ -282,9 +287,12 @@ from django_components import component
282
287
 
283
288
  @component.register("calendar")
284
289
  class Calendar(component.Component):
285
- # Templates inside `[your apps]/components` dir and `[project root]/components` dir will be automatically found. To customize which template to use based on context
286
- # you can override def get_template_name() instead of specifying the below variable.
287
- template_name = "calendar/template.html"
290
+ # Templates inside `[your apps]/components` dir and `[project root]/components` dir
291
+ # will be automatically found. To customize which template to use based on context
292
+ # you can override method `get_template_name` instead of specifying `template_name`.
293
+ #
294
+ # `template_name` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS
295
+ template_name = "template.html"
288
296
 
289
297
  # This component takes one parameter, a date string to show in the template
290
298
  def get_context_data(self, date):
@@ -292,9 +300,10 @@ class Calendar(component.Component):
292
300
  "date": date,
293
301
  }
294
302
 
303
+ # Both `css` and `js` can be relative to dir where `calendar.py` is, or relative to STATICFILES_DIRS
295
304
  class Media:
296
- css = "calendar/style.css"
297
- js = "calendar/script.js"
305
+ css = "style.css"
306
+ js = "script.js"
298
307
  ```
299
308
 
300
309
  And voilá!! We've created our first component.
@@ -337,7 +346,7 @@ This makes it easy to create small components without having to create a separat
337
346
 
338
347
  Note that the `t.django_html`, `t.css`, and `t.js` types are used to specify the type of the template, CSS, and JS files, respectively. This is not necessary, but if you're using VSCode with the [Python Inline Source Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=samwillis.python-inline-source) extension, it will give you syntax highlighting for the template, CSS, and JS.
339
348
 
340
- ## Use the component in a template
349
+ ## Use components in templates
341
350
 
342
351
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
343
352
 
@@ -382,13 +391,143 @@ The output from the above template will be:
382
391
 
383
392
  This makes it possible to organize your front-end around reusable components. Instead of relying on template tags and keeping your CSS and Javascript in the static directory.
384
393
 
394
+ ## Use components outside of templates
395
+
396
+ _New in version 0.81_
397
+
398
+ Components can be rendered outside of Django templates, calling them as regular functions ("React-style").
399
+
400
+ The component class defines `render` and `render_to_response` class methods. These methods accept positional args, kwargs, and slots, offering the same flexibility as the `{% component %}` tag:
401
+
402
+ ```py
403
+ class SimpleComponent(component.Component):
404
+ template = """
405
+ {% load component_tags %}
406
+ hello: {{ hello }}
407
+ foo: {{ foo }}
408
+ kwargs: {{ kwargs|safe }}
409
+ slot_first: {% slot "first" required %}{% endslot %}
410
+ """
411
+
412
+ def get_context_data(self, arg1, arg2, **kwargs):
413
+ return {
414
+ "hello": arg1,
415
+ "foo": arg2,
416
+ "kwargs": kwargs,
417
+ }
418
+
419
+ rendered = SimpleComponent.render(
420
+ args=["world", "bar"],
421
+ kwargs={"kw1": "test", "kw2": "ooo"},
422
+ slots={"first": "FIRST_SLOT"},
423
+ context={"from_context": 98},
424
+ )
425
+ ```
426
+
427
+ Renders:
428
+
429
+ ```
430
+ hello: world
431
+ foo: bar
432
+ kwargs: {'kw1': 'test', 'kw2': 'ooo'}
433
+ slot_first: FIRST_SLOT
434
+ ```
435
+
436
+ ### Inputs of `render` and `render_to_response`
437
+
438
+ Both `render` and `render_to_response` accept the same input:
439
+
440
+ ```py
441
+ Component.render(
442
+ context: Mapping | django.template.Context | None = None,
443
+ args: List[Any] | None = None,
444
+ kwargs: Dict[str, Any] | None = None,
445
+ slots: Dict[str, str | SafeString | SlotRenderFunc] | None = None,
446
+ escape_slots_content: bool = True
447
+ ) -> str:
448
+ ```
449
+
450
+ - _`args`_ - Positional args for the component. This is the same as calling the component
451
+ as `{% component "my_comp" arg1 arg2 ... %}`
452
+
453
+ - _`kwargs`_ - Keyword args for the component. This is the same as calling the component
454
+ as `{% component "my_comp" key1=val1 key2=val2 ... %}`
455
+
456
+ - _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
457
+ Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
458
+ or [`SlotRenderFunc`](#slotrenderfunc).
459
+
460
+ - _`escape_slots_content`_ - Whether the content from `slots` should be escaped. `True` by default to prevent XSS attacks. If you disable escaping, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
461
+
462
+ - _`context`_ - A context (dictionary or Django's Context) within which the component
463
+ is rendered. The keys on the context can be accessed from within the template.
464
+ - NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
465
+ component's args and kwargs.
466
+
467
+ #### `SlotRenderFunc`
468
+
469
+ When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
470
+
471
+ The function has following signature:
472
+
473
+ ```py
474
+ def render_func(
475
+ context: Context,
476
+ data: Dict[str, Any],
477
+ slot_ref: SlotRef,
478
+ ) -> str | SafeString:
479
+ return nodelist.render(ctx)
480
+ ```
481
+
482
+ - _`context`_ - Django's Context available to the Slot Node.
483
+ - _`data`_ - Data passed to the `{% slot %}` tag. See [Scoped Slots](#scoped-slots).
484
+ - _`slot_ref`_ - The default slot content. See [Accessing original content of slots](#accessing-original-content-of-slots).
485
+ - NOTE: The slot is lazily evaluated. To render the slot, convert it to string with `str(slot_ref)`.
486
+
487
+ Example:
488
+ ```py
489
+ def footer_slot(ctx, data, slot_ref):
490
+ return f"""
491
+ SLOT_DATA: {data['abc']}
492
+ ORIGINAL: {slot_ref}
493
+ """
494
+
495
+ MyComponent.render_to_response(
496
+ slots={
497
+ "footer": footer_slot,
498
+ },
499
+ )
500
+ ```
501
+
502
+ ### Response class of `render_to_response`
503
+
504
+ While `render` method returns a plain string, `render_to_response` wraps the rendered content in a "Response" class. By default, this is `django.http.HttpResponse`.
505
+
506
+ If you want to use a different Response class in `render_to_response`, set the `Component.response_class` attribute:
507
+
508
+ ```py
509
+ class MyResponse(HttpResponse):
510
+ def __init__(self, *args, **kwargs) -> None:
511
+ super().__init__(*args, **kwargs)
512
+ # Configure response
513
+ self.headers = ...
514
+ self.status = ...
515
+
516
+ class SimpleComponent(component.Component):
517
+ response_class = MyResponse
518
+ template: types.django_html = "HELLO"
519
+
520
+ response = SimpleComponent.render_to_response()
521
+ assert isinstance(response, MyResponse)
522
+ ```
523
+
385
524
  ## Use components as views
386
525
 
387
526
  _New in version 0.34_
388
527
 
389
528
  Components can now be used as views. To do this, `Component` subclasses Django's `View` class. This means that you can use all of the [methods](https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#view) of `View` in your component. For example, you can override `get` and `post` to handle GET and POST requests, respectively.
390
529
 
391
- In addition, `Component` now has a `render_to_response` method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
530
+ In addition, `Component` now has a [`render_to_response`](#inputs-of-render-and-render_to_response) method that renders the component template based on the provided context and slots' data and returns an `HttpResponse` object.
392
531
 
393
532
  Here's an example of a calendar component defined as a view:
394
533
 
@@ -417,7 +556,7 @@ class Calendar(component.Component):
417
556
  slots = {
418
557
  "header": "Calendar header",
419
558
  }
420
- return self.render_to_response(context, slots)
559
+ return self.render_to_response(context=context, slots=slots)
421
560
  ```
422
561
 
423
562
  Then, to use this component as a view, you should create a `urls.py` file in your components directory, and add a path to the component's view:
@@ -1535,7 +1674,207 @@ If you find yourself using the `only` modifier often, you can set the [context_b
1535
1674
 
1536
1675
  Components can also access the outer context in their context methods like `get_context_data` by accessing the property `self.outer_context`.
1537
1676
 
1538
- ## Rendering JS and CSS dependencies
1677
+ ## Defining HTML/JS/CSS files
1678
+
1679
+ django_component's management of files builds on top of [Django's `Media` class](https://docs.djangoproject.com/en/5.0/topics/forms/media/).
1680
+
1681
+ To be familiar with how Django handles static files, we recommend reading also:
1682
+ - [How to manage static files (e.g. images, JavaScript, CSS)](https://docs.djangoproject.com/en/5.0/howto/static-files/)
1683
+
1684
+ ### Defining file paths relative to component or static dirs
1685
+
1686
+ As seen in the [getting started example](#create-your-first-component), to associate HTML/JS/CSS
1687
+ files with a component, you set them as `template_name`, `Media.js` and `Media.css` respectively:
1688
+
1689
+ ```py
1690
+ # In a file [project root]/components/calendar/calendar.py
1691
+ from django_components import component
1692
+
1693
+ @component.register("calendar")
1694
+ class Calendar(component.Component):
1695
+ template_name = "template.html"
1696
+
1697
+ class Media:
1698
+ css = "style.css"
1699
+ js = "script.js"
1700
+ ```
1701
+
1702
+ In the example above, the files are defined relative to the directory where `component.py` is.
1703
+
1704
+ Alternatively, you can specify the file paths relative to the directories set in `STATICFILES_DIRS`.
1705
+
1706
+ Assuming that `STATICFILES_DIRS` contains path `[project root]/components`, we can rewrite the example as:
1707
+
1708
+ ```py
1709
+ # In a file [project root]/components/calendar/calendar.py
1710
+ from django_components import component
1711
+
1712
+ @component.register("calendar")
1713
+ class Calendar(component.Component):
1714
+ template_name = "calendar/template.html"
1715
+
1716
+ class Media:
1717
+ css = "calendar/style.css"
1718
+ js = "calendar/script.js"
1719
+ ```
1720
+
1721
+ NOTE: In case of conflict, the preference goes to resolving the files relative to the component's directory.
1722
+
1723
+ ### Defining multiple paths
1724
+
1725
+ Each component can have only a single template. However, you can define as many JS or CSS files as you want using a list.
1726
+
1727
+ ```py
1728
+ class MyComponent(component.Component):
1729
+ class Media:
1730
+ js = ["path/to/script1.js", "path/to/script2.js"]
1731
+ css = ["path/to/style1.css", "path/to/style2.css"]
1732
+ ```
1733
+
1734
+ ### Configuring CSS Media Types
1735
+
1736
+ You can define which stylesheets will be associated with which
1737
+ [CSS Media types](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#targeting_media_types). You do so by defining CSS files as a dictionary.
1738
+
1739
+ See the corresponding [Django Documentation](https://docs.djangoproject.com/en/5.0/topics/forms/media/#css).
1740
+
1741
+ Again, you can set either a single file or a list of files per media type:
1742
+
1743
+ ```py
1744
+ class MyComponent(component.Component):
1745
+ class Media:
1746
+ css = {
1747
+ "all": "path/to/style1.css",
1748
+ "print": "path/to/style2.css",
1749
+ }
1750
+ ```
1751
+
1752
+ ```py
1753
+ class MyComponent(component.Component):
1754
+ class Media:
1755
+ css = {
1756
+ "all": ["path/to/style1.css", "path/to/style2.css"],
1757
+ "print": ["path/to/style3.css", "path/to/style4.css"],
1758
+ }
1759
+ ```
1760
+
1761
+ NOTE: When you define CSS as a string or a list, the `all` media type is implied.
1762
+
1763
+
1764
+ ### Supported types for file paths
1765
+
1766
+ File paths can be any of:
1767
+ - `str`
1768
+ - `bytes`
1769
+ - `PathLike` (`__fspath__` method)
1770
+ - `SafeData` (`__html__` method)
1771
+ - `Callable` that returns any of the above, evaluated at class creation (`__new__`)
1772
+
1773
+ ```py
1774
+ from pathlib import Path
1775
+
1776
+ from django.utils.safestring import mark_safe
1777
+
1778
+ class SimpleComponent(component.Component):
1779
+ class Media:
1780
+ css = [
1781
+ mark_safe('<link href="/static/calendar/style.css" rel="stylesheet" />'),
1782
+ Path("calendar/style1.css"),
1783
+ "calendar/style2.css",
1784
+ b"calendar/style3.css",
1785
+ lambda: "calendar/style4.css",
1786
+ ]
1787
+ js = [
1788
+ mark_safe('<script src="/static/calendar/script.js"></script>'),
1789
+ Path("calendar/script1.js"),
1790
+ "calendar/script2.js",
1791
+ b"calendar/script3.js",
1792
+ lambda: "calendar/script4.js",
1793
+ ]
1794
+ ```
1795
+
1796
+ ### Path as objects
1797
+
1798
+ In the example [above](#supported-types-for-file-paths), you could see that when we used `mark_safe` to mark a string as a `SafeString`, we had to define the full `<script>`/`<link>` tag.
1799
+
1800
+ This is an extension of Django's [Paths as objects](https://docs.djangoproject.com/en/5.0/topics/forms/media/#paths-as-objects) feature, where "safe" strings are taken as is, and accessed only at render time.
1801
+
1802
+ Because of that, the paths defined as "safe" strings are NEVER resolved, neither relative to component's directory, nor relative to `STATICFILES_DIRS`.
1803
+
1804
+ "Safe" strings can be used to lazily resolve a path, or to customize the `<script>` or `<link>` tag for individual paths:
1805
+
1806
+ ```py
1807
+ class LazyJsPath:
1808
+ def __init__(self, static_path: str) -> None:
1809
+ self.static_path = static_path
1810
+
1811
+ def __html__(self):
1812
+ full_path = static(self.static_path)
1813
+ return format_html(
1814
+ f'<script type="module" src="{full_path}"></script>'
1815
+ )
1816
+
1817
+ @component.register("calendar")
1818
+ class Calendar(component.Component):
1819
+ template_name = "calendar/template.html"
1820
+
1821
+ def get_context_data(self, date):
1822
+ return {
1823
+ "date": date,
1824
+ }
1825
+
1826
+ class Media:
1827
+ css = "calendar/style.css"
1828
+ js = [
1829
+ # <script> tag constructed by Media class
1830
+ "calendar/script1.js",
1831
+ # Custom <script> tag
1832
+ LazyJsPath("calendar/script2.js"),
1833
+ ]
1834
+ ```
1835
+
1836
+ ### Customize how paths are rendered into HTML tags with `media_class`
1837
+
1838
+ Sometimes you may need to change how all CSS `<link>` or JS `<script>` tags are rendered for a given component. You can achieve this by providing your own subclass of [Django's `Media` class](https://docs.djangoproject.com/en/5.0/topics/forms/media) to component's `media_class` attribute.
1839
+
1840
+ Normally, the JS and CSS paths are passed to `Media` class, which decides how the paths are resolved and how the `<link>` and `<script>` tags are constructed.
1841
+
1842
+ To change how the tags are constructed, you can override the [`Media.render_js` and `Media.render_css` methods](https://github.com/django/django/blob/fa7848146738a9fe1d415ee4808664e54739eeb7/django/forms/widgets.py#L102):
1843
+
1844
+ ```py
1845
+ from django.forms.widgets import Media
1846
+ from django_components import component
1847
+
1848
+ class MyMedia(Media):
1849
+ # Same as original Media.render_js, except
1850
+ # the `<script>` tag has also `type="module"`
1851
+ def render_js(self):
1852
+ tags = []
1853
+ for path in self._js:
1854
+ if hasattr(path, "__html__"):
1855
+ tag = path.__html__()
1856
+ else:
1857
+ tag = format_html(
1858
+ '<script type="module" src="{}"></script>',
1859
+ self.absolute_path(path)
1860
+ )
1861
+ return tags
1862
+
1863
+ @component.register("calendar")
1864
+ class Calendar(component.Component):
1865
+ template_name = "calendar/template.html"
1866
+
1867
+ class Media:
1868
+ css = "calendar/style.css"
1869
+ js = "calendar/script.js"
1870
+
1871
+ # Override the behavior of Media class
1872
+ media_class = MyMedia
1873
+ ```
1874
+
1875
+ NOTE: The instance of the `Media` class (or it's subclass) is available under `Component.media` after the class creation (`__new__`).
1876
+
1877
+ ## Rendering JS/CSS dependencies
1539
1878
 
1540
1879
  The JS and CSS files included in components are not automatically rendered.
1541
1880
  Instead, use the following tags to specify where to render the dependencies: