django-components 0.91__tar.gz → 0.93__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 (64) hide show
  1. {django_components-0.91/src/django_components.egg-info → django_components-0.93}/PKG-INFO +805 -121
  2. {django_components-0.91 → django_components-0.93}/README.md +805 -121
  3. {django_components-0.91 → django_components-0.93}/pyproject.toml +35 -1
  4. {django_components-0.91 → django_components-0.93}/src/django_components/__init__.py +12 -1
  5. {django_components-0.91 → django_components-0.93}/src/django_components/attributes.py +23 -14
  6. {django_components-0.91 → django_components-0.93}/src/django_components/component.py +187 -81
  7. {django_components-0.91 → django_components-0.93}/src/django_components/component_registry.py +53 -5
  8. {django_components-0.91 → django_components-0.93}/src/django_components/context.py +2 -0
  9. django_components-0.93/src/django_components/expression.py +311 -0
  10. {django_components-0.91 → django_components-0.93}/src/django_components/library.py +11 -8
  11. {django_components-0.91 → django_components-0.93}/src/django_components/node.py +19 -0
  12. django_components-0.93/src/django_components/provide.py +63 -0
  13. {django_components-0.91 → django_components-0.93}/src/django_components/slots.py +177 -76
  14. {django_components-0.91 → django_components-0.93}/src/django_components/tag_formatter.py +7 -4
  15. {django_components-0.91 → django_components-0.93}/src/django_components/template_parser.py +1 -86
  16. {django_components-0.91 → django_components-0.93}/src/django_components/templatetags/component_tags.py +254 -181
  17. {django_components-0.91 → django_components-0.93}/src/django_components/types.py +4 -2
  18. {django_components-0.91 → django_components-0.93/src/django_components.egg-info}/PKG-INFO +805 -121
  19. {django_components-0.91 → django_components-0.93}/src/django_components.egg-info/SOURCES.txt +1 -0
  20. {django_components-0.91 → django_components-0.93}/tests/test_attributes.py +32 -0
  21. {django_components-0.91 → django_components-0.93}/tests/test_component.py +83 -1
  22. {django_components-0.91 → django_components-0.93}/tests/test_component_as_view.py +59 -11
  23. django_components-0.93/tests/test_expression.py +846 -0
  24. {django_components-0.91 → django_components-0.93}/tests/test_registry.py +82 -1
  25. {django_components-0.91 → django_components-0.93}/tests/test_template_parser.py +20 -19
  26. {django_components-0.91 → django_components-0.93}/tests/test_templatetags_provide.py +88 -8
  27. {django_components-0.91 → django_components-0.93}/tests/test_templatetags_slot_fill.py +164 -2
  28. django_components-0.91/src/django_components/expression.py +0 -63
  29. django_components-0.91/src/django_components/provide.py +0 -52
  30. {django_components-0.91 → django_components-0.93}/LICENSE +0 -0
  31. {django_components-0.91 → django_components-0.93}/setup.cfg +0 -0
  32. {django_components-0.91 → django_components-0.93}/src/django_components/app_settings.py +0 -0
  33. {django_components-0.91 → django_components-0.93}/src/django_components/apps.py +0 -0
  34. {django_components-0.91 → django_components-0.93}/src/django_components/autodiscover.py +0 -0
  35. {django_components-0.91 → django_components-0.93}/src/django_components/component_media.py +0 -0
  36. {django_components-0.91 → django_components-0.93}/src/django_components/logger.py +0 -0
  37. {django_components-0.91 → django_components-0.93}/src/django_components/management/__init__.py +0 -0
  38. {django_components-0.91 → django_components-0.93}/src/django_components/management/commands/__init__.py +0 -0
  39. {django_components-0.91 → django_components-0.93}/src/django_components/management/commands/startcomponent.py +0 -0
  40. {django_components-0.91 → django_components-0.93}/src/django_components/management/commands/upgradecomponent.py +0 -0
  41. {django_components-0.91 → django_components-0.93}/src/django_components/middleware.py +0 -0
  42. {django_components-0.91 → django_components-0.93}/src/django_components/py.typed +0 -0
  43. {django_components-0.91 → django_components-0.93}/src/django_components/safer_staticfiles/__init__.py +0 -0
  44. {django_components-0.91 → django_components-0.93}/src/django_components/safer_staticfiles/apps.py +0 -0
  45. {django_components-0.91 → django_components-0.93}/src/django_components/template_loader.py +0 -0
  46. {django_components-0.91 → django_components-0.93}/src/django_components/templatetags/__init__.py +0 -0
  47. {django_components-0.91 → django_components-0.93}/src/django_components/utils.py +0 -0
  48. {django_components-0.91 → django_components-0.93}/src/django_components.egg-info/dependency_links.txt +0 -0
  49. {django_components-0.91 → django_components-0.93}/src/django_components.egg-info/requires.txt +0 -0
  50. {django_components-0.91 → django_components-0.93}/src/django_components.egg-info/top_level.txt +0 -0
  51. {django_components-0.91 → django_components-0.93}/tests/test_autodiscover.py +0 -0
  52. {django_components-0.91 → django_components-0.93}/tests/test_command_startcomponent.py +0 -0
  53. {django_components-0.91 → django_components-0.93}/tests/test_component_media.py +0 -0
  54. {django_components-0.91 → django_components-0.93}/tests/test_context.py +0 -0
  55. {django_components-0.91 → django_components-0.93}/tests/test_dependency_rendering.py +0 -0
  56. {django_components-0.91 → django_components-0.93}/tests/test_safer_staticfiles.py +0 -0
  57. {django_components-0.91 → django_components-0.93}/tests/test_settings.py +0 -0
  58. {django_components-0.91 → django_components-0.93}/tests/test_tag_formatter.py +0 -0
  59. {django_components-0.91 → django_components-0.93}/tests/test_template_loader.py +0 -0
  60. {django_components-0.91 → django_components-0.93}/tests/test_templatetags.py +0 -0
  61. {django_components-0.91 → django_components-0.93}/tests/test_templatetags_component.py +0 -0
  62. {django_components-0.91 → django_components-0.93}/tests/test_templatetags_templating.py +0 -0
  63. {django_components-0.91 → django_components-0.93}/tests/test_utils.py +0 -0
  64. {django_components-0.91 → django_components-0.93}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.91
3
+ Version: 0.93
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
@@ -22,14 +22,29 @@ Description-Content-Type: text/markdown
22
22
  License-File: LICENSE
23
23
  Requires-Dist: Django>=4.2
24
24
 
25
- # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
25
+ # <img src="https://raw.githubusercontent.com/EmilStenstrom/django-components/master/logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
26
26
 
27
- <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>
28
- <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
27
+ [![PyPI - Version](https://img.shields.io/pypi/v/django-components)](https://pypi.org/project/django-components/) [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-components)](https://pypi.org/project/django-components/) [![PyPI - License](https://img.shields.io/pypi/l/django-components)](https://EmilStenstrom.github.io/django-components/latest/license/) [![PyPI - Downloads](https://img.shields.io/pypi/dm/django-components)](https://pypistats.org/packages/django-components) [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/EmilStenstrom/django-components/tests.yml)](https://github.com/EmilStenstrom/django-components/actions/workflows/tests.yml)
29
28
 
30
- A way to create simple reusable template components in Django.
29
+ [**Docs (Work in progress)**](https://EmilStenstrom.github.io/django-components/latest/)
31
30
 
32
- It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Components look like this:
31
+ Create simple reusable template components in Django
32
+
33
+ ## Features
34
+
35
+ <!-- FIXME Links -->
36
+
37
+ - ✨ **Reusable components**: Create components that can be reused in different parts of your project, or even in different projects.
38
+ - 📁 **Single file components**: Keep your Python, CSS, Javascript and HTML in one place (if you wish)
39
+ - 🎰 **Slots**: Define slots in your components to make them more flexible.
40
+ - 💻 **CLI**: A command line interface to help you create new components.
41
+ - 🚀 **Wide compatibility**: Works with [modern and LTS versions of Django](https://emilstenstrom.github.io/django-components/latest/user_guide/requirements_compatibility).
42
+ - **Load assets**: Automatically load the right CSS and Javascript files for your components, with [our middleware](https://emilstenstrom.github.io/django-components/latest/user_guide/creating_using_components/middleware).
43
+
44
+
45
+ ## Summary
46
+
47
+ It lets you create "template components", that contains both the template, the Javascript and the CSS needed to generate the front end code you need for a modern app. Use components like this:
33
48
 
34
49
  ```htmldjango
35
50
  {% component "calendar" date="2015-06-19" %}{% endcomponent %}
@@ -48,7 +63,7 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
48
63
  - [Release notes](#release-notes)
49
64
  - [Security notes 🚨](#security-notes-)
50
65
  - [Installation](#installation)
51
- - [Compatiblity](#compatiblity)
66
+ - [Compatibility](#compatibility)
52
67
  - [Create your first component](#create-your-first-component)
53
68
  - [Using single-file components](#using-single-file-components)
54
69
  - [Use components in templates](#use-components-in-templates)
@@ -57,8 +72,9 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
57
72
  - [Use components as views](#use-components-as-views)
58
73
  - [Autodiscovery](#autodiscovery)
59
74
  - [Using slots in templates](#using-slots-in-templates)
60
- - [Passing data to components](#passing-data-to-components)
75
+ - [Accessing data passed to the component](#accessing-data-passed-to-the-component)
61
76
  - [Rendering HTML attributes](#rendering-html-attributes)
77
+ - [Template tag syntax](#template-tag-syntax)
62
78
  - [Prop drilling and dependency injection (provide / inject)](#prop-drilling-and-dependency-injection-provide--inject)
63
79
  - [Component context and scope](#component-context-and-scope)
64
80
  - [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter)
@@ -67,12 +83,26 @@ And this is what gets rendered (plus the CSS and Javascript you've specified):
67
83
  - [Available settings](#available-settings)
68
84
  - [Logging and debugging](#logging-and-debugging)
69
85
  - [Management Command](#management-command)
86
+ - [Writing and sharing component libraries](#writing-and-sharing-component-libraries)
70
87
  - [Community examples](#community-examples)
71
88
  - [Running django-components project locally](#running-django-components-project-locally)
72
89
  - [Development guides](#development-guides)
73
90
 
74
91
  ## Release notes
75
92
 
93
+ **Version 0.93**
94
+ - Spread operator `...dict` inside template tags. See [Spread operator](#spread-operator))
95
+ - Use template tags inside string literals in component inputs. See [Use template tags inside component inputs](#use-template-tags-inside-component-inputs))
96
+ - Dynamic slots, fills and provides - The `name` argument for these can now be a variable, a template expression, or via spread operator
97
+ - Component library authors can now configure `CONTEXT_BEHAVIOR` and `TAG_FORMATTER` settings independently from user settings.
98
+
99
+ 🚨📢 **Version 0.92**
100
+ - BREAKING CHANGE: `Component` class is no longer a subclass of `View`. To configure the `View` class, set the `Component.View` nested class. HTTP methods like `get` or `post` can still be defined directly on `Component` class, and `Component.as_view()` internally calls `Component.View.as_view()`. (See [Modifying the View class](#modifying-the-view-class))
101
+
102
+ - The inputs (args, kwargs, slots, context, ...) that you pass to `Component.render()` can be accessed from within `get_context_data`, `get_template_string` and `get_template_name` via `self.input`. (See [Accessing data passed to the component](#accessing-data-passed-to-the-component))
103
+
104
+ - Typing: `Component` class supports generics that specify types for `Component.render` (See [Adding type hints with Generics](#adding-type-hints-with-generics))
105
+
76
106
  **Version 0.90**
77
107
  - All tags (`component`, `slot`, `fill`, ...) now support "self-closing" or "inline" form, where you can omit the closing tag:
78
108
  ```django
@@ -279,7 +309,7 @@ TEMPLATES = [
279
309
 
280
310
  Read on to find out how to build your first component!
281
311
 
282
- ## Compatiblity
312
+ ## Compatibility
283
313
 
284
314
  Django-components supports all supported combinations versions of [Django](https://docs.djangoproject.com/en/dev/faq/install/#what-python-version-can-i-use-with-django) and [Python](https://devguide.python.org/versions/#versions).
285
315
 
@@ -311,9 +341,9 @@ A component in django-components is the combination of four things: CSS, Javascr
311
341
 
312
342
  Start by creating empty files in the structure above.
313
343
 
314
- First you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
344
+ First, you need a CSS file. Be sure to prefix all rules with a unique class so they don't clash with other rules.
315
345
 
316
- ```css
346
+ ```css title="[project root]/components/calendar/style.css"
317
347
  /* In a file called [project root]/components/calendar/style.css */
318
348
  .calendar-component {
319
349
  width: 200px;
@@ -326,7 +356,7 @@ First you need a CSS file. Be sure to prefix all rules with a unique class so th
326
356
 
327
357
  Then you need a javascript file that specifies how you interact with this component. You are free to use any javascript framework you want. A good way to make sure this component doesn't clash with other components is to define all code inside an anonymous function that calls itself. This makes all variables defined only be defined inside this component and not affect other components.
328
358
 
329
- ```js
359
+ ```js title="[project root]/components/calendar/script.js"
330
360
  /* In a file called [project root]/components/calendar/script.js */
331
361
  (function () {
332
362
  if (document.querySelector(".calendar-component")) {
@@ -339,7 +369,7 @@ Then you need a javascript file that specifies how you interact with this compon
339
369
 
340
370
  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.
341
371
 
342
- ```htmldjango
372
+ ```htmldjango title="[project root]/components/calendar/calendar.html"
343
373
  {# In a file called [project root]/components/calendar/template.html #}
344
374
  <div class="calendar-component">Today's date is <span>{{ date }}</span></div>
345
375
  ```
@@ -348,7 +378,7 @@ Finally, we use django-components to tie this together. Start by creating a file
348
378
 
349
379
  Inside this file we create a Component by inheriting from the Component class and specifying the context method. We also register the global component registry so that we easily can render it anywhere in our templates.
350
380
 
351
- ```python
381
+ ```python title="[project root]/components/calendar/calendar.py"
352
382
  # In a file called [project root]/components/calendar/calendar.py
353
383
  from django_components import Component, register
354
384
 
@@ -379,7 +409,7 @@ And voilá!! We've created our first component.
379
409
 
380
410
  Components can also be defined in a single file, which is useful for small components. To do this, you can use the `template`, `js`, and `css` class attributes instead of the `template_name` and `Media`. For example, here's the calendar component from above, defined in a single file:
381
411
 
382
- ```python
412
+ ```python title="[project root]/components/calendar.py"
383
413
  # In a file called [project root]/components/calendar.py
384
414
  from django_components import Component, register, types
385
415
 
@@ -554,7 +584,7 @@ Component.render(
554
584
  context: Mapping | django.template.Context | None = None,
555
585
  args: List[Any] | None = None,
556
586
  kwargs: Dict[str, Any] | None = None,
557
- slots: Dict[str, str | SafeString | SlotRenderFunc] | None = None,
587
+ slots: Dict[str, str | SafeString | SlotFunc] | None = None,
558
588
  escape_slots_content: bool = True
559
589
  ) -> str:
560
590
  ```
@@ -567,7 +597,7 @@ Component.render(
567
597
 
568
598
  - _`slots`_ - Component slot fills. This is the same as pasing `{% fill %}` tags to the component.
569
599
  Accepts a dictionary of `{ slot_name: slot_content }` where `slot_content` can be a string
570
- or [`SlotRenderFunc`](#slotrenderfunc).
600
+ or [`SlotFunc`](#slotfunc).
571
601
 
572
602
  - _`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.
573
603
 
@@ -576,7 +606,7 @@ Component.render(
576
606
  - NOTE: In "isolated" mode, context is NOT accessible, and data MUST be passed via
577
607
  component's args and kwargs.
578
608
 
579
- #### `SlotRenderFunc`
609
+ #### `SlotFunc`
580
610
 
581
611
  When rendering components with slots in `render` or `render_to_response`, you can pass either a string or a function.
582
612
 
@@ -612,6 +642,58 @@ MyComponent.render_to_response(
612
642
  )
613
643
  ```
614
644
 
645
+ ### Adding type hints with Generics
646
+
647
+ The `Component` class optionally accepts type parameters
648
+ that allow you to specify the types of args, kwargs, slots, and
649
+ data.
650
+
651
+ ```py
652
+ from typing import NotRequired, Tuple, TypedDict, SlotFunc
653
+
654
+ # Positional inputs - Tuple
655
+ Args = Tuple[int, str]
656
+
657
+ # Kwargs inputs - Mapping
658
+ class Kwargs(TypedDict):
659
+ variable: str
660
+ another: int
661
+ maybe_var: NotRequired[int]
662
+
663
+ # Data returned from `get_context_data` - Mapping
664
+ class Data(TypedDict):
665
+ variable: str
666
+
667
+ # The data available to the `my_slot` scoped slot
668
+ class MySlotData(TypedDict):
669
+ value: int
670
+
671
+ # Slot functions - Mapping
672
+ class Slots(TypedDict):
673
+ # Use SlotFunc for slot functions.
674
+ # The generic specifies the `data` dictionary
675
+ my_slot: NotRequired[SlotFunc[MySlotData]]
676
+
677
+ class Button(Component[Args, Kwargs, Data, Slots]):
678
+ def get_context_data(self, variable, another):
679
+ return {
680
+ "variable": variable,
681
+ }
682
+ ```
683
+
684
+ When you then call `Component.render` or `Component.render_to_response`, you will get type hints:
685
+
686
+ ```py
687
+ Button.render(
688
+ # Error: First arg must be `int`, got `float`
689
+ args=(1.25, "abc"),
690
+ # Error: Key "another" is missing
691
+ kwargs={
692
+ "variable": "text",
693
+ },
694
+ )
695
+ ```
696
+
615
697
  ### Response class of `render_to_response`
616
698
 
617
699
  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`.
@@ -638,15 +720,22 @@ assert isinstance(response, MyResponse)
638
720
 
639
721
  _New in version 0.34_
640
722
 
641
- 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.
723
+ _Note: Since 0.92, Component no longer subclasses View. To configure the View class, set the nested `Component.View` class_
724
+
725
+ Components can now be used as views:
726
+ - Components define the `Component.as_view()` class method that can be used the same as [`View.as_view()`](https://docs.djangoproject.com/en/5.1/ref/class-based-views/base/#django.views.generic.base.View.as_view).
642
727
 
643
- 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.
728
+ - By default, you can define GET, POST or other HTTP handlers directly on the Component, same as you do with [View](https://docs.djangoproject.com/en/5.1/ref/class-based-views/base/#view). For example, you can override `get` and `post` to handle GET and POST requests, respectively.
729
+
730
+ - 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.
731
+
732
+ ### Component as view example
644
733
 
645
734
  Here's an example of a calendar component defined as a view:
646
735
 
647
736
  ```python
648
737
  # In a file called [project root]/components/calendar.py
649
- from django_components import Component, register
738
+ from django_components import Component, ComponentView, register
650
739
 
651
740
  @register("calendar")
652
741
  class Calendar(Component):
@@ -662,6 +751,7 @@ class Calendar(Component):
662
751
  </div>
663
752
  """
664
753
 
754
+ # Handle GET requests
665
755
  def get(self, request, *args, **kwargs):
666
756
  context = {
667
757
  "date": request.GET.get("date", "2020-06-06"),
@@ -669,7 +759,11 @@ class Calendar(Component):
669
759
  slots = {
670
760
  "header": "Calendar header",
671
761
  }
672
- return self.render_to_response(context=context, slots=slots)
762
+ # Return HttpResponse with the rendered content
763
+ return self.render_to_response(
764
+ context=context,
765
+ slots=slots,
766
+ )
673
767
  ```
674
768
 
675
769
  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:
@@ -684,6 +778,9 @@ urlpatterns = [
684
778
  ]
685
779
  ```
686
780
 
781
+ `Component.as_view()` is a shorthand for calling [`View.as_view()`](https://docs.djangoproject.com/en/5.1/ref/class-based-views/base/#django.views.generic.base.View.as_view) and passing the component
782
+ instance as one of the arguments.
783
+
687
784
  Remember to add `__init__.py` to your components directory, so that Django can find the `urls.py` file.
688
785
 
689
786
  Finally, include the component's urls in your project's `urls.py` file:
@@ -697,10 +794,77 @@ urlpatterns = [
697
794
  ]
698
795
  ```
699
796
 
700
- Note: slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set `escape_slots_content=False` in the `render_to_response` method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
797
+ Note: Slots content are automatically escaped by default to prevent XSS attacks. To disable escaping, set `escape_slots_content=False` in the `render_to_response` method. If you do so, you should make sure that any content you pass to the slots is safe, especially if it comes from user input.
701
798
 
702
799
  If you're planning on passing an HTML string, check Django's use of [`format_html`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.html.format_html) and [`mark_safe`](https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.safestring.mark_safe).
703
800
 
801
+ ### Modifying the View class
802
+
803
+ The View class that handles the requests is defined on `Component.View`.
804
+
805
+ When you define a GET or POST handlers on the `Component` class, like so:
806
+
807
+ ```py
808
+ class MyComponent(Component):
809
+ def get(self, request, *args, **kwargs):
810
+ return self.render_to_response(
811
+ context={
812
+ "date": request.GET.get("date", "2020-06-06"),
813
+ },
814
+ )
815
+
816
+ def post(self, request, *args, **kwargs) -> HttpResponse:
817
+ variable = request.POST.get("variable")
818
+ return self.render_to_response(
819
+ kwargs={"variable": variable}
820
+ )
821
+ ```
822
+
823
+ Then the request is still handled by `Component.View.get()` or `Component.View.post()`
824
+ methods. However, by default, `Component.View.get()` points to `Component.get()`, and so on.
825
+
826
+ ```py
827
+ class ComponentView(View):
828
+ component: Component = None
829
+ ...
830
+
831
+ def get(self, request, *args, **kwargs):
832
+ return self.component.get(request, *args, **kwargs)
833
+
834
+ def post(self, request, *args, **kwargs):
835
+ return self.component.post(request, *args, **kwargs)
836
+
837
+ ...
838
+ ```
839
+
840
+ If you want to define your own `View` class, you need to:
841
+ 1. Set the class as `Component.View`
842
+ 2. Subclass from `ComponentView`, so the View instance has access to the component instance.
843
+
844
+ In the example below, we added extra logic into `View.setup()`.
845
+
846
+ Note that the POST handler is still defined at the top. This is because `View` subclasses `ComponentView`, which defines the `post()` method that calls `Component.post()`.
847
+
848
+ If you were to overwrite the `View.post()` method, then `Component.post()` would be ignored.
849
+
850
+ ```py
851
+ from django_components import Component, ComponentView
852
+
853
+ class MyComponent(Component):
854
+
855
+ def post(self, request, *args, **kwargs) -> HttpResponse:
856
+ variable = request.POST.get("variable")
857
+ return self.component.render_to_response(
858
+ kwargs={"variable": variable}
859
+ )
860
+
861
+ class View(ComponentView):
862
+ def setup(self, request, *args, **kwargs):
863
+ super(request, *args, **kwargs)
864
+
865
+ do_something_extra(request, *args, **kwargs)
866
+ ```
867
+
704
868
  ## Registering components
705
869
 
706
870
  In previous examples you could repeatedly see us using `@register()` to "register"
@@ -794,8 +958,8 @@ registry.clear()
794
958
 
795
959
  ### Registering components to custom ComponentRegistry
796
960
 
797
- In rare cases, you may want to manage your own instance of `ComponentRegistry`,
798
- or register components onto a different `Library` instance than the default one.
961
+ If you are writing a component library to be shared with others, you may want to manage your own instance of `ComponentRegistry`
962
+ and register components onto a different `Library` instance than the default one.
799
963
 
800
964
  The `Library` instance can be set at instantiation of `ComponentRegistry`. If omitted,
801
965
  then the default Library instance from django_components is used.
@@ -822,6 +986,34 @@ class MyComponent(Component):
822
986
 
823
987
  NOTE: The Library instance can be accessed under `library` attribute of `ComponentRegistry`.
824
988
 
989
+ ### ComponentRegistry settings
990
+
991
+ When you are creating an instance of `ComponentRegistry`, you can define the components' behavior within the template.
992
+
993
+ The registry accepts these settings:
994
+ - `CONTEXT_BEHAVIOR`
995
+ - `TAG_FORMATTER`
996
+
997
+ ```py
998
+ from django.template import Library
999
+ from django_components import ComponentRegistry, RegistrySettings
1000
+
1001
+ register = library = django.template.Library()
1002
+ comp_registry = ComponentRegistry(
1003
+ library=library,
1004
+ settings=RegistrySettings(
1005
+ CONTEXT_BEHAVIOR="isolated",
1006
+ TAG_FORMATTER="django_components.component_formatter",
1007
+ ),
1008
+ )
1009
+ ```
1010
+
1011
+ These settings are [the same as the ones you can set for django_components](#available-settings).
1012
+
1013
+ In fact, when you set `COMPONENT.tag_formatter` or `COMPONENT.context_behavior`, these are forwarded to the default `ComponentRegistry`.
1014
+
1015
+ This makes it possible to have multiple registries with different settings in one projects, and makes sharing of component libraries possible.
1016
+
825
1017
  ## Autodiscovery
826
1018
 
827
1019
  Every component that you want to use in the template with the `{% component %}` tag needs to be registered with the ComponentRegistry. Normally, we use the `@register` decorator for that:
@@ -864,7 +1056,7 @@ If you are using autodiscovery, keep a few points in mind:
864
1056
  - Components inside the auto-imported files still need to be registered with `@register()`
865
1057
  - 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).
866
1058
 
867
- Autodiscovery can be disabled in the [settings](#disable-autodiscovery).
1059
+ Autodiscovery can be disabled in the [settings](#autodiscover---toggle-autodiscovery).
868
1060
 
869
1061
  ### Manually trigger autodiscovery
870
1062
 
@@ -1303,115 +1495,107 @@ to the same name. This raises an error:
1303
1495
  {% endcomponent %}
1304
1496
  ```
1305
1497
 
1306
- ## Passing data to components
1498
+ ### Dynamic slots and fills
1307
1499
 
1308
- As seen above, you can pass arguments to components like so:
1500
+ Until now, we were declaring slot and fill names statically, as a string literal, e.g.
1309
1501
 
1310
1502
  ```django
1311
- <body>
1312
- {% component "calendar" date="2015-06-19" %}
1313
- {% endcomponent %}
1314
- </body>
1503
+ {% slot "content" / %}
1315
1504
  ```
1316
1505
 
1317
- ### Special characters
1506
+ However, sometimes you may want to generate slots based on the given input. One example of this is [a table component like that of Vuetify](https://vuetifyjs.com/en/api/v-data-table/), which creates a header and an item slots for each user-defined column.
1318
1507
 
1319
- _New in version 0.71_:
1508
+ In django_components you can achieve the same, simply by using a variable (or a [template expression](#use-template-tags-inside-component-inputs)) instead of a string literal:
1320
1509
 
1321
- Keyword arguments can contain special characters `# @ . - _`, so keywords like
1322
- so are still valid:
1510
+ ```django
1511
+ <table>
1512
+ <tr>
1513
+ {% for header in headers %}
1514
+ <th>
1515
+ {% slot "header-{{ header.key }}" value=header.title %}
1516
+ {{ header.title }}
1517
+ {% endslot %}
1518
+ </th>
1519
+ {% endfor %}
1520
+ </tr>
1521
+ </table>
1522
+ ```
1523
+
1524
+ When using the component, you can either set the fill explicitly:
1323
1525
 
1324
1526
  ```django
1325
- <body>
1326
- {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
1327
- </body>
1527
+ {% component "table" headers=headers items=items %}
1528
+ {% fill "header-name" data="data" %}
1529
+ <b>{{ data.value }}</b>
1530
+ {% endfill %}
1531
+ {% endcomponent %}
1328
1532
  ```
1329
1533
 
1330
- These can then be accessed inside `get_context_data` so:
1534
+ Or also use a variable:
1331
1535
 
1332
- ```py
1333
- @register("calendar")
1334
- class Calendar(Component):
1335
- # Since # . @ - are not valid identifiers, we have to
1336
- # use `**kwargs` so the method can accept these args.
1337
- def get_context_data(self, **kwargs):
1338
- return {
1339
- "date": kwargs["my-date"],
1340
- "id": kwargs["#some_id"],
1341
- "on_click": kwargs["@click.native"]
1342
- }
1536
+ ```django
1537
+ {% component "table" headers=headers items=items %}
1538
+ {# Make only the active column bold #}
1539
+ {% fill "header-{{ active_header_name }}" data="data" %}
1540
+ <b>{{ data.value }}</b>
1541
+ {% endfill %}
1542
+ {% endcomponent %}
1343
1543
  ```
1344
1544
 
1345
- ### Pass dictonary by its key-value pairs
1545
+ > NOTE: It's better to use static slot names whenever possible for clarity. The dynamic slot names should be reserved for advanced use only.
1346
1546
 
1347
- _New in version 0.74_:
1547
+ Lastly, in rare cases, you can also pass the slot name via [the spread operator](#spread-operator). This is possible, because the slot name argument is actually a shortcut for a `name` keyword argument.
1348
1548
 
1349
- Sometimes, a component may expect a dictionary as one of its inputs.
1549
+ So this:
1350
1550
 
1351
- Most commonly, this happens when a component accepts a dictionary
1352
- of HTML attributes (usually called `attrs`) to pass to the underlying template.
1551
+ ```django
1552
+ {% slot "content" / %}
1553
+ ```
1353
1554
 
1354
- In such cases, we may want to define some HTML attributes statically, and other dynamically.
1355
- But for that, we need to define this dictionary on Python side:
1555
+ is the same as:
1356
1556
 
1357
- ```py
1358
- @register("my_comp")
1359
- class MyComp(Component):
1360
- template = """
1361
- {% component "other" attrs=attrs / %}
1362
- """
1557
+ ```django
1558
+ {% slot name="content" / %}
1559
+ ```
1363
1560
 
1364
- def get_context_data(self, some_id: str):
1365
- attrs = {
1366
- "class": "pa-4 flex",
1367
- "data-some-id": some_id,
1368
- "@click.stop": "onClickHandler",
1369
- }
1370
- return {"attrs": attrs}
1561
+ So it's possible to define a `name` key on a dictionary, and then spread that onto the slot tag:
1562
+
1563
+ ```django
1564
+ {# slot_props = {"name": "content"} #}
1565
+ {% slot ...slot_props / %}
1371
1566
  ```
1372
1567
 
1373
- But as you can see in the case above, the event handler `@click.stop` and styling `pa-4 flex`
1374
- are disconnected from the template. If the component grew in size and we moved the HTML
1375
- to a separate file, we would have hard time reasoning about the component's template.
1568
+ ## Accessing data passed to the component
1376
1569
 
1377
- Luckily, there's a better way.
1570
+ When you call `Component.render` or `Component.render_to_response`, the inputs to these methods can be accessed from within the instance under `self.input`.
1378
1571
 
1379
- When we want to pass a dictionary to a component, we can define individual key-value pairs
1380
- as component kwargs, so we can keep all the relevant information in the template. For that,
1381
- we prefix the key with the name of the dict and `:`. So key `class` of input `attrs` becomes
1382
- `attrs:class`. And our example becomes:
1572
+ This means that you can use `self.input` inside:
1573
+ - `get_context_data`
1574
+ - `get_template_name`
1575
+ - `get_template_string`
1383
1576
 
1384
- ```py
1385
- @register("my_comp")
1386
- class MyComp(Component):
1387
- template = """
1388
- {% component "other"
1389
- attrs:class="pa-4 flex"
1390
- attrs:data-some-id=some_id
1391
- attrs:@click.stop="onClickHandler"
1392
- / %}
1393
- """
1577
+ `self.input` is defined only for the duration of `Component.render`, and returns `None` when called outside of this.
1394
1578
 
1395
- def get_context_data(self, some_id: str):
1396
- return {"some_id": some_id}
1397
- ```
1579
+ `self.input` has the same fields as the input to `Component.render`:
1398
1580
 
1399
- Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
1581
+ ```py
1582
+ class TestComponent(Component):
1583
+ def get_context_data(self, var1, var2, variable, another, **attrs):
1584
+ assert self.input.args == (123, "str")
1585
+ assert self.input.kwargs == {"variable": "test", "another": 1}
1586
+ assert self.input.slots == {"my_slot": "MY_SLOT"}
1587
+ assert isinstance(self.input.context, Context)
1400
1588
 
1401
- ```django
1402
- {% component "other"
1403
- attrs:class="pa-4 flex"
1404
- attrs:data-some-id=some_id
1405
- attrs:@click.stop="onClickHandler"
1406
- / %}
1407
- ```
1589
+ return {
1590
+ "variable": variable,
1591
+ }
1408
1592
 
1409
- > Note: It is NOT possible to define nested dictionaries, so
1410
- > `attrs:my_key:two=2` would be interpreted as:
1411
- >
1412
- > ```py
1413
- > {"attrs": {"my_key:two": 2}}
1414
- > ```
1593
+ rendered = TestComponent.render(
1594
+ kwargs={"variable": "test", "another": 1},
1595
+ args=(123, "str"),
1596
+ slots={"my_slot": "MY_SLOT"},
1597
+ )
1598
+ ```
1415
1599
 
1416
1600
  ## Rendering HTML attributes
1417
1601
 
@@ -1789,6 +1973,266 @@ attributes_to_string(attrs)
1789
1973
  # 'class="my-class text-red pa-4" data-id="123" required'
1790
1974
  ```
1791
1975
 
1976
+ ## Template tag syntax
1977
+
1978
+ All template tags in django_component, like `{% component %}` or `{% slot %}`, and so on,
1979
+ support extra syntax that makes it possible to write components like in Vue or React (JSX).
1980
+
1981
+ ### Self-closing tags
1982
+
1983
+ When you have a tag like `{% component %}` or `{% slot %}`, but it has no content, you can simply append a forward slash `/` at the end, instead of writing out the closing tags like `{% endcomponent %}` or `{% endslot %}`:
1984
+
1985
+ So this:
1986
+
1987
+ ```django
1988
+ {% component "button" %}{% endcomponent %}
1989
+ ```
1990
+
1991
+ becomes
1992
+
1993
+ ```django
1994
+ {% component "button" / %}
1995
+ ```
1996
+
1997
+ ### Special characters
1998
+
1999
+ _New in version 0.71_:
2000
+
2001
+ Keyword arguments can contain special characters `# @ . - _`, so keywords like
2002
+ so are still valid:
2003
+
2004
+ ```django
2005
+ <body>
2006
+ {% component "calendar" my-date="2015-06-19" @click.native=do_something #some_id=True / %}
2007
+ </body>
2008
+ ```
2009
+
2010
+ These can then be accessed inside `get_context_data` so:
2011
+
2012
+ ```py
2013
+ @register("calendar")
2014
+ class Calendar(Component):
2015
+ # Since # . @ - are not valid identifiers, we have to
2016
+ # use `**kwargs` so the method can accept these args.
2017
+ def get_context_data(self, **kwargs):
2018
+ return {
2019
+ "date": kwargs["my-date"],
2020
+ "id": kwargs["#some_id"],
2021
+ "on_click": kwargs["@click.native"]
2022
+ }
2023
+ ```
2024
+
2025
+ ### Spread operator
2026
+
2027
+ _New in version 0.93_:
2028
+
2029
+ Instead of passing keyword arguments one-by-one:
2030
+
2031
+ ```django
2032
+ {% component "calendar" title="How to abc" date="2015-06-19" author="John Wick" / %}
2033
+ ```
2034
+
2035
+ You can use a spread operator `...dict` to apply key-value pairs from a dictionary:
2036
+
2037
+ ```py
2038
+ post_data = {
2039
+ "title": "How to...",
2040
+ "date": "2015-06-19",
2041
+ "author": "John Wick",
2042
+ }
2043
+ ```
2044
+
2045
+ ```django
2046
+ {% component "calendar" ...post_data / %}
2047
+ ```
2048
+
2049
+ This behaves similar to [JSX's spread operator](https://kevinyckim33.medium.com/jsx-spread-operator-component-props-meaning-3c9bcadd2493)
2050
+ or [Vue's `v-bind`](https://vuejs.org/api/built-in-directives.html#v-bind).
2051
+
2052
+ Spread operators are treated as keyword arguments, which means that:
2053
+ 1. Spread operators must come after positional arguments.
2054
+ 2. You cannot use spread operators for [positional-only arguments](https://martinxpn.medium.com/positional-only-and-keyword-only-arguments-in-python-37-100-days-of-python-310c311657b0).
2055
+
2056
+ Other than that, you can use spread operators multiple times, and even put keyword arguments in-between or after them:
2057
+
2058
+ ```django
2059
+ {% component "calendar" ...post_data id=post.id ...extra / %}
2060
+ ```
2061
+
2062
+ In a case of conflicts, the values added later (right-most) overwrite previous values.
2063
+
2064
+ ### Use template tags inside component inputs
2065
+
2066
+ _New in version 0.93_
2067
+
2068
+ When passing data around, sometimes you may need to do light transformations, like negating booleans or filtering lists.
2069
+
2070
+ Normally, what you would have to do is to define ALL the variables
2071
+ inside `get_context_data()`. But this can get messy if your components contain a lot of logic.
2072
+
2073
+ ```py
2074
+ @register("calendar")
2075
+ class Calendar(Component):
2076
+ def get_context_data(self, id: str, editable: bool):
2077
+ return {
2078
+ "editable": editable,
2079
+ "readonly": not editable,
2080
+ "input_id": f"input-{id}",
2081
+ "icon_id": f"icon-{id}",
2082
+ ...
2083
+ }
2084
+ ```
2085
+
2086
+ Instead, template tags in django_components (`{% component %}`, `{% slot %}`, `{% provide %}`, etc) allow you to treat literal string values as templates:
2087
+
2088
+ ```django
2089
+ {% component 'blog_post'
2090
+ "As positional arg {# yay #}"
2091
+ title="{{ person.first_name }} {{ person.last_name }}"
2092
+ id="{% random_int 10 20 %}"
2093
+ readonly="{{ editable|not }}"
2094
+ author="John Wick {# TODO: parametrize #}"
2095
+ / %}
2096
+ ```
2097
+
2098
+ In the example above:
2099
+ - Component `test` receives a positional argument with value `"As positional arg "`. The comment is omitted.
2100
+ - Kwarg `title` is passed as a string, e.g. `John Doe`
2101
+ - Kwarg `id` is passed as `int`, e.g. `15`
2102
+ - Kwarg `readonly` is passed as `bool`, e.g. `False`
2103
+ - Kwarg `author` is passed as a string, e.g. `John Wick ` (Comment omitted)
2104
+
2105
+ This is inspired by [django-cotton](https://github.com/wrabit/django-cotton#template-expressions-in-attributes).
2106
+
2107
+ #### Passing data as string vs original values
2108
+
2109
+ Sometimes you may want to use the template tags to transform
2110
+ or generate the data that is then passed to the component.
2111
+
2112
+ The data doesn't necessarily have to be strings. In the example above, the kwarg `id` was passed as an integer, NOT a string.
2113
+
2114
+ Although the string literals for components inputs are treated as regular Django templates, there is one special case:
2115
+
2116
+ When the string literal contains only a single template tag, with no extra text, then the value is passed as the original type instead of a string.
2117
+
2118
+ Here, `page` is an integer:
2119
+
2120
+ ```django
2121
+ {% component 'blog_post' page="{% random_int 10 20 %}" / %}
2122
+ ```
2123
+
2124
+ Here, `page` is a string:
2125
+
2126
+ ```django
2127
+ {% component 'blog_post' page=" {% random_int 10 20 %} " / %}
2128
+ ```
2129
+
2130
+ And same applies to the `{{ }}` variable tags:
2131
+
2132
+ Here, `items` is a list:
2133
+
2134
+ ```django
2135
+ {% component 'cat_list' items="{{ cats|slice:':2' }}" / %}
2136
+ ```
2137
+
2138
+ Here, `items` is a string:
2139
+
2140
+ ```django
2141
+ {% component 'cat_list' items="{{ cats|slice:':2' }} See more" / %}
2142
+ ```
2143
+
2144
+ #### Evaluating Python expressions in template
2145
+
2146
+ You can even go a step further and have a similar experience to Vue or React,
2147
+ where you can evaluate arbitrary code expressions:
2148
+
2149
+ ```jsx
2150
+ <MyForm
2151
+ value={ isEnabled ? inputValue : null }
2152
+ />
2153
+ ```
2154
+
2155
+ Similar is possible with [`django-expr`](https://pypi.org/project/django-expr/), which adds an `expr` tag and filter that you can use to evaluate Python expressions from within the template:
2156
+
2157
+ ```django
2158
+ {% component "my_form"
2159
+ value="{% expr 'input_value if is_enabled else None' %}"
2160
+ / %}
2161
+ ```
2162
+
2163
+ > Note: Never use this feature to mix business logic and template logic. Business logic should still be in the view!
2164
+
2165
+ ### Pass dictonary by its key-value pairs
2166
+
2167
+ _New in version 0.74_:
2168
+
2169
+ Sometimes, a component may expect a dictionary as one of its inputs.
2170
+
2171
+ Most commonly, this happens when a component accepts a dictionary
2172
+ of HTML attributes (usually called `attrs`) to pass to the underlying template.
2173
+
2174
+ In such cases, we may want to define some HTML attributes statically, and other dynamically.
2175
+ But for that, we need to define this dictionary on Python side:
2176
+
2177
+ ```py
2178
+ @register("my_comp")
2179
+ class MyComp(Component):
2180
+ template = """
2181
+ {% component "other" attrs=attrs / %}
2182
+ """
2183
+
2184
+ def get_context_data(self, some_id: str):
2185
+ attrs = {
2186
+ "class": "pa-4 flex",
2187
+ "data-some-id": some_id,
2188
+ "@click.stop": "onClickHandler",
2189
+ }
2190
+ return {"attrs": attrs}
2191
+ ```
2192
+
2193
+ But as you can see in the case above, the event handler `@click.stop` and styling `pa-4 flex`
2194
+ are disconnected from the template. If the component grew in size and we moved the HTML
2195
+ to a separate file, we would have hard time reasoning about the component's template.
2196
+
2197
+ Luckily, there's a better way.
2198
+
2199
+ When we want to pass a dictionary to a component, we can define individual key-value pairs
2200
+ as component kwargs, so we can keep all the relevant information in the template. For that,
2201
+ we prefix the key with the name of the dict and `:`. So key `class` of input `attrs` becomes
2202
+ `attrs:class`. And our example becomes:
2203
+
2204
+ ```py
2205
+ @register("my_comp")
2206
+ class MyComp(Component):
2207
+ template = """
2208
+ {% component "other"
2209
+ attrs:class="pa-4 flex"
2210
+ attrs:data-some-id=some_id
2211
+ attrs:@click.stop="onClickHandler"
2212
+ / %}
2213
+ """
2214
+
2215
+ def get_context_data(self, some_id: str):
2216
+ return {"some_id": some_id}
2217
+ ```
2218
+
2219
+ Sweet! Now all the relevant HTML is inside the template, and we can move it to a separate file with confidence:
2220
+
2221
+ ```django
2222
+ {% component "other"
2223
+ attrs:class="pa-4 flex"
2224
+ attrs:data-some-id=some_id
2225
+ attrs:@click.stop="onClickHandler"
2226
+ / %}
2227
+ ```
2228
+
2229
+ > Note: It is NOT possible to define nested dictionaries, so
2230
+ > `attrs:my_key:two=2` would be interpreted as:
2231
+ >
2232
+ > ```py
2233
+ > {"attrs": {"my_key:two": 2}}
2234
+ > ```
2235
+
1792
2236
  ## Prop drilling and dependency injection (provide / inject)
1793
2237
 
1794
2238
  _New in version 0.80_:
@@ -1835,10 +2279,7 @@ First we use the `{% provide %}` tag to define the data we want to "provide" (ma
1835
2279
 
1836
2280
  Notice that the `provide` tag REQUIRES a name as a first argument. This is the _key_ by which we can then access the data passed to this tag.
1837
2281
 
1838
- `provide` tag _key_, similarly to the _name_ argument in `component` or `slot` tags, has these requirements:
1839
-
1840
- - The _key_ must be a string literal
1841
- - It must be a valid identifier (AKA a valid Python variable name)
2282
+ `provide` tag name must resolve to a valid identifier (AKA a valid Python variable name).
1842
2283
 
1843
2284
  Once you've set the name, you define the data you want to "provide" by passing it as keyword arguments. This is similar to how you pass data to the `{% with %}` tag.
1844
2285
 
@@ -1851,6 +2292,15 @@ Once you've set the name, you define the data you want to "provide" by passing i
1851
2292
  > {% endprovide %}
1852
2293
  > ```
1853
2294
 
2295
+ Similarly to [slots and fills](#dynamic-slots-and-fills), also provide's name argument can be set dynamically via a variable, a template expression, or a spread operator:
2296
+
2297
+ ```django
2298
+ {% provide name=name ... %}
2299
+ ...
2300
+ {% provide %}
2301
+ </table>
2302
+ ```
2303
+
1854
2304
  ### Using `inject()` method
1855
2305
 
1856
2306
  To "inject" (access) the data defined on the `provide` tag, you can use the `inject()` method inside of `get_context_data()`.
@@ -1868,7 +2318,7 @@ class ChildComponent(Component):
1868
2318
  return {}
1869
2319
  ```
1870
2320
 
1871
- First argument to `inject` is the _key_ of the provided data. This
2321
+ First argument to `inject` is the _key_ (or _name_) of the provided data. This
1872
2322
  must match the string that you used in the `provide` tag. If no provider
1873
2323
  with given key is found, `inject` raises a `KeyError`.
1874
2324
 
@@ -1925,7 +2375,7 @@ With this in mind, the `{% component %}` tag behaves similarly to `{% include %}
1925
2375
  And just like with `{% include %}`, if you don't want a specific component template to have access to the parent context, add `only` to the `{% component %}` tag:
1926
2376
 
1927
2377
  ```htmldjango
1928
- {% component "calendar" date="2015-06-19" only %}{% endcomponent %}
2378
+ {% component "calendar" date="2015-06-19" only / %}
1929
2379
  ```
1930
2380
 
1931
2381
  NOTE: `{% csrf_token %}` tags need access to the top-level context, and they will not function properly if they are rendered in a component that is called with the `only` modifier.
@@ -2323,9 +2773,9 @@ COMPONENTS = {
2323
2773
 
2324
2774
  All library settings are handled from a global `COMPONENTS` variable that is read from `settings.py`. By default you don't need it set, there are resonable defaults.
2325
2775
 
2326
- ### Configure the module where components are loaded from
2776
+ ### `libraries` - Load component modules
2327
2777
 
2328
- Configure the location where components are loaded. To do this, add a `COMPONENTS` variable to you `settings.py` with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
2778
+ Configure the locations where components are loaded. To do this, add a `COMPONENTS` variable to you `settings.py` with a list of python paths to load. This allows you to build a structure of components that are independent from your apps.
2329
2779
 
2330
2780
  ```python
2331
2781
  COMPONENTS = {
@@ -2365,7 +2815,7 @@ from django_components import import_libraries
2365
2815
  import_libraries()
2366
2816
  ```
2367
2817
 
2368
- ### Disable autodiscovery
2818
+ ### `autodiscover` - Toggle autodiscovery
2369
2819
 
2370
2820
  If you specify all the component locations with the setting above and have a lot of apps, you can (very) slightly speed things up by disabling autodiscovery.
2371
2821
 
@@ -2375,9 +2825,11 @@ COMPONENTS = {
2375
2825
  }
2376
2826
  ```
2377
2827
 
2378
- ### Tune the template cache
2828
+ ### `template_cache_size` - Tune the template cache
2829
+
2830
+ Each time a template is rendered it is cached to a global in-memory cache (using Python's `lru_cache` decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.
2379
2831
 
2380
- Each time a template is rendered it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up. By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
2832
+ By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are using the `template` method of a component to render lots of dynamic templates, you can increase this number. To remove the cache limit altogether and cache everything, set template_cache_size to `None`.
2381
2833
 
2382
2834
  ```python
2383
2835
  COMPONENTS = {
@@ -2385,7 +2837,7 @@ COMPONENTS = {
2385
2837
  }
2386
2838
  ```
2387
2839
 
2388
- ### Context behavior setting
2840
+ ### `context_behavior` - Make components isolated (or not)
2389
2841
 
2390
2842
  > NOTE: `context_behavior` and `slot_context_behavior` options were merged in v0.70.
2391
2843
  >
@@ -2490,9 +2942,8 @@ But since `"cheese"` is not defined there, it's empty.
2490
2942
 
2491
2943
  Notice that the variables defined with the `{% with %}` tag are ignored inside the `{% fill %}` tag with the `"isolated"` mode.
2492
2944
 
2493
- ### Tag formatter setting
2494
-
2495
- Set the [`TagFormatter`](#available-tagformatters) instance.
2945
+ ### `tag_formatter` - Change how components are used in templates
2946
+ Sets the [`TagFormatter`](#available-tagformatters) instance. See the section [Customizing component tags with TagFormatter](#customizing-component-tags-with-tagformatter).
2496
2947
 
2497
2948
  Can be set either as direct reference, or as an import string;
2498
2949
 
@@ -2616,6 +3067,239 @@ python manage.py startcomponent my_component --dry-run
2616
3067
 
2617
3068
  This will simulate the creation of `my_component` without creating any files.
2618
3069
 
3070
+ ## Writing and sharing component libraries
3071
+
3072
+ You can publish and share your components for others to use. Here are the steps to do so:
3073
+
3074
+ ### Writing component libraries
3075
+
3076
+ 1. Create a Django project with the following structure:
3077
+
3078
+ ```txt
3079
+ project/
3080
+ |-- myapp/
3081
+ |-- __init__.py
3082
+ |-- apps.py
3083
+ |-- templates/
3084
+ |-- table/
3085
+ |-- table.py
3086
+ |-- table.js
3087
+ |-- table.css
3088
+ |-- table.html
3089
+ |-- menu.py <--- single-file component
3090
+ |-- templatetags/
3091
+ |-- __init__.py
3092
+ |-- mytags.py
3093
+ ```
3094
+
3095
+ 2. Create custom `Library` and `ComponentRegistry` instances in `mytags.py`
3096
+
3097
+ This will be the entrypoint for using the components inside Django templates.
3098
+
3099
+ Remember that Django requires the `Library` instance to be accessible under the `register` variable ([See Django docs](https://docs.djangoproject.com/en/dev/howto/custom-template-tags)):
3100
+
3101
+ ```py
3102
+ from django.template import Library
3103
+ from django_components import ComponentRegistry, RegistrySettings
3104
+
3105
+ register = library = django.template.Library()
3106
+ comp_registry = ComponentRegistry(
3107
+ library=library,
3108
+ settings=RegistrySettings(
3109
+ CONTEXT_BEHAVIOR="isolated",
3110
+ TAG_FORMATTER="django_components.component_formatter",
3111
+ ),
3112
+ )
3113
+ ```
3114
+
3115
+ As you can see above, this is also the place where we configure how our components should behave, using the `settings` argument. If omitted, default settings are used.
3116
+
3117
+ For library authors, we recommend setting `CONTEXT_BEHAVIOR` to `"isolated"`, so that the state cannot leak into the components, and so the components' behavior is configured solely through the inputs. This means that the components will be more predictable and easier to debug.
3118
+
3119
+ Next, you can decide how will others use your components by settingt the `TAG_FORMATTER` options.
3120
+
3121
+ If omitted or set to `"django_components.component_formatter"`,
3122
+ your components will be used like this:
3123
+
3124
+ ```django
3125
+ {% component "table" items=items headers=headers %}
3126
+ {% endcomponent %}
3127
+ ```
3128
+
3129
+ Or you can use `"django_components.component_shorthand_formatter"`
3130
+ to use components like so:
3131
+
3132
+ ```django
3133
+ {% table items=items headers=headers %}
3134
+ {% endtable %}
3135
+ ```
3136
+
3137
+ Or you can define a [custom TagFormatter](#tagformatter).
3138
+
3139
+ Either way, these settings will be scoped only to your components. So, in the user code, there may be components side-by-side that use different formatters:
3140
+
3141
+ ```django
3142
+ {% load mytags %}
3143
+
3144
+ {# Component from your library "mytags", using the "shorthand" formatter #}
3145
+ {% table items=items headers=header %}
3146
+ {% endtable %}
3147
+
3148
+ {# User-created components using the default settings #}
3149
+ {% component "my_comp" title="Abc..." %}
3150
+ {% endcomponent %}
3151
+ ```
3152
+
3153
+ 3. Write your components and register them with your instance of `ComponentRegistry`
3154
+
3155
+ There's one difference when you are writing components that are to be shared, and that's that the components must be explicitly registered with your instance of `ComponentRegistry` from the previous step.
3156
+
3157
+ For better user experience, you can also define the types for the args, kwargs, slots and data.
3158
+
3159
+ It's also a good idea to have a common prefix for your components, so they can be easily distinguished from users' components. In the example below, we use the prefix `my_` / `My`.
3160
+
3161
+ ```py
3162
+ from typing import Dict, NotRequired, Optional, Tuple, TypedDict
3163
+
3164
+ from django_components import Component, SlotFunc, register, types
3165
+
3166
+ from myapp.templatetags.mytags import comp_registry
3167
+
3168
+ # Define the types
3169
+ class EmptyDict(TypedDict):
3170
+ pass
3171
+
3172
+ type MyMenuArgs = Tuple[int, str]
3173
+
3174
+ class MyMenuSlots(TypedDict):
3175
+ default: NotRequired[Optional[SlotFunc[EmptyDict]]]
3176
+
3177
+ class MyMenuProps(TypedDict):
3178
+ vertical: NotRequired[bool]
3179
+ klass: NotRequired[str]
3180
+ style: NotRequired[str]
3181
+
3182
+ # Define the component
3183
+ # NOTE: Don't forget to set the `registry`!
3184
+ @register("my_menu", registry=comp_registry)
3185
+ class MyMenu(Component[MyMenuArgs, MyMenuProps, MyMenuSlots, Any]):
3186
+ def get_context_data(
3187
+ self,
3188
+ *args,
3189
+ attrs: Optional[Dict] = None,
3190
+ ):
3191
+ return {
3192
+ "attrs": attrs,
3193
+ }
3194
+
3195
+ template: types.django_html = """
3196
+ {# Load django_components template tags #}
3197
+ {% load component_tags %}
3198
+
3199
+ <div {% html_attrs attrs class="my-menu" %}>
3200
+ <div class="my-menu__content">
3201
+ {% slot "default" default / %}
3202
+ </div>
3203
+ </div>
3204
+ """
3205
+ ```
3206
+
3207
+ 4. Import the components in `apps.py`
3208
+
3209
+ Normally, users rely on [autodiscovery](#autodiscovery) and `STATICFILES_DIRS` to load the component files.
3210
+
3211
+ Since you, as the library author, are not in control of the file system, it is recommended to load the components manually.
3212
+
3213
+ We recommend doing this in the `AppConfig.ready()` hook of your `apps.py`:
3214
+
3215
+ ```py
3216
+ from django.apps import AppConfig
3217
+
3218
+ class MyAppConfig(AppConfig):
3219
+ default_auto_field = "django.db.models.BigAutoField"
3220
+ name = "myapp"
3221
+
3222
+ # This is the code that gets run when user adds myapp
3223
+ # to Django's INSTALLED_APPS
3224
+ def ready(self) -> None:
3225
+ # Import the components that you want to make available
3226
+ # inside the templates.
3227
+ from myapp.templates import (
3228
+ menu,
3229
+ table,
3230
+ )
3231
+ ```
3232
+
3233
+ Note that you can also include any other startup logic within `AppConfig.ready()`.
3234
+
3235
+ And that's it! The next step is to publish it.
3236
+
3237
+ ### Publishing component libraries
3238
+
3239
+ Once you are ready to share your library, you need to build
3240
+ a distribution and then publish it to PyPI.
3241
+
3242
+ django_components uses the [`build`](https://build.pypa.io/en/stable/) utility to build a distribution:
3243
+
3244
+ ```bash
3245
+ python -m build --sdist --wheel --outdir dist/ .
3246
+ ```
3247
+
3248
+ And to publish to PyPI, you can use `twine` ([See Python user guide](https://packaging.python.org/en/latest/tutorials/packaging-projects/#uploading-the-distribution-archives))
3249
+
3250
+ ```bash
3251
+ twine upload --repository pypi dist/* -u __token__ -p <PyPI_TOKEN>
3252
+ ```
3253
+
3254
+ Notes on publishing:
3255
+ - The user of the package NEEDS to have installed and configured `django_components`.
3256
+ - If you use components where the HTML / CSS / JS files are separate, you may need to define `MANIFEST.in` to include those files with the distribution ([see user guide](https://setuptools.pypa.io/en/latest/userguide/miscellaneous.html)).
3257
+
3258
+ ### Installing and using component libraries
3259
+
3260
+ After the package has been published, all that remains is to install it in other django projects:
3261
+
3262
+ 1. Install the package:
3263
+
3264
+ ```bash
3265
+ pip install myapp
3266
+ ```
3267
+
3268
+ 2. Add the package to `INSTALLED_APPS`
3269
+
3270
+ ```py
3271
+ INSTALLED_APPS = [
3272
+ ...
3273
+ "myapp",
3274
+ ]
3275
+ ```
3276
+
3277
+ 3. Optionally add the template tags to the `builtins`, so you don't have to call `{% load mytags %}` in every template:
3278
+
3279
+ ```py
3280
+ TEMPLATES = [
3281
+ {
3282
+ ...,
3283
+ 'OPTIONS': {
3284
+ 'context_processors': [
3285
+ ...
3286
+ ],
3287
+ 'builtins': [
3288
+ 'myapp.templatetags.mytags',
3289
+ ]
3290
+ },
3291
+ },
3292
+ ]
3293
+ ```
3294
+
3295
+ 4. And, at last, you can use the components in your own project!
3296
+
3297
+ ```django
3298
+ {% my_menu title="Abc..." %}
3299
+ Hello World!
3300
+ {% endmy_menu %}
3301
+ ```
3302
+
2619
3303
  ## Community examples
2620
3304
 
2621
3305
  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.